【问题标题】:How to Implement linq on dictionary in C#?如何在 C# 中的字典上实现 linq?
【发布时间】:2015-12-29 12:29:29
【问题描述】:

我在使用 C# 字典中的 linq 创建在线考试门户时遇到问题。我关心的是获得在线考试类别,子类别。我向数据库服务器发出请求以获取我的数据。现在我的数据在前端可用,但我试图以一种方便的方式获取记录,以便我可以将我的数据划分为类别、子类别和问题。例如,我希望我的标题和类别如下:-

一般知识

  • 基本常识
  • 世界地理
  • 发明
  • 荣誉和奖项

数学

  • 时间和速度
  • 代数
  • 帐户

但是使用下面给定的代码我的结果正在显示

一般知识

  • 基本常识
  • 基本常识
  • 基本常识

这会根据每个子类别的问题数量重复。

我使用的代码是

 public ActionResult getOnlineTestTitle()
    {
        List<GopreadyOnlineTest> search;
        if (Session["OnlineTest"] == null)
        {
             search= GopreadyOnlineTest.Search(WebConfigurationManager.ConnectionStrings["liveData"].ConnectionString).ToList();
             Session["OnlineTest"] = search;
        }
        else
        {
            search = (List<GopreadyOnlineTest>)Session["OnlineTest"];
        }            
        List<string> categoryName = search.Select(x => x.CategoryName).Distinct().ToList();
        Dictionary<string, List<GopreadyOnlineTest>> result2 = new Dictionary<string, List<GopreadyOnlineTest>>();
        foreach (string item in categoryName)
        {
            result2.Add(item, search.Where(s => s.CategoryName.ToUpper() == item.ToUpper()).ToList());
        }
        return Json(result2, JsonRequestBehavior.AllowGet);            
    }

这是我的过程,它正在向我返回数据。

alter proc Quiz_SEARCH
(
    @CategoryName varchar(200) = null,
    @SubCategoryName varchar(200) = null
)
as
select c.catId as 'CategoryId', c.catName as 'CategoryName', s.subCatId as 'SubCategoryId', s.subCatName as 'SubCategoryName',
 q.question as 'Question', q.opta as 'OptionA',
q.optb as 'OptionB', q.optc as 'OptionC', q.optd as 'OptionD', q.answer, q.quesDescription as 'QuestionDescription'
from quizcategory c join quizsubcategory s on c.catid=s.catid
join quizquestion q on s.subcatid = q.subcatid
where 
(@CategoryName is null or [CatName]=@CategoryName)
and
(@subcategoryName is null or [SubCatName]=@SubCategoryName)

     ----------

请帮助解决这个问题。如果我输入以下行来解决问题,则不允许我这样做。

result2.Add(item, search.Where(s => s.CategoryName.ToUpper() == item.ToUpper()).Select(x=>x.SubCategoryName).Distinct().ToList());

这是我动态设计页面的 jquery。

function GetOnlineTestTitle() {    
    $.ajax({
        type: "GET",
        url: "getOnlineTestTitle",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: true,
        cache: false,
        success: function (msg) { 
            var htmlString = '';
            alert(JSON.stringify(msg));
            $("#examList").html(htmlString);
            $.each(msg, function (key, val) {
                if (val.length != 0) {
                    htmlString += '<li><h3>' + key + '</h3></li>';
                }
                $.each(val, function (key2, val2) {
                    htmlString += '<li><a href="#"><b>'+val2.SubCategoryName+'</b></a></li>';
                });
            });
            $('#examList').append(htmlString);
        },
        error: function (msg) {
            alert("Error:" + JSON.stringify(msg));
        }
    });
}

【问题讨论】:

  • 我猜你应该使用GroupBy
  • 我也试过了。但没有成功。:-)
  • 你能发布你的视图来显示这个类别吗?
  • 我也面临同样的问题。
  • @kcwu 我正在使用 ajax 调用来设计布局。

标签: c# jquery linq dictionary razor


【解决方案1】:

您可以使用 LINQ 中的 GroupBy 方法来执行此操作,请参见下文。

假设您的 GopreadyOnlineTest 类是这样的:

public class GopreadyOnlineTest
{
    public string CategoryId { get; set; }
    public string CategoryName { get; set; }
    public string SubCategoryId { get; set; }
    public string SubCategoryName { get; set; }
    public string Question { get; set; }
    public string OptionA { get; set; }
    public string OptionB { get; set; }
    public string OptionC { get; set; }
    public string OptionD { get; set; }
    public string QuestionDescription { get; set; }
}

而您的 List&lt;GopreadyOnlineTest&gt; search 变量包含一些类似的数据:

this.search = new List<GopreadyOnlineTest> 
{
    new GopreadyOnlineTest { CategoryName = "General Knowledge", SubCategoryName = "Basic General Knowledge" },
    new GopreadyOnlineTest { CategoryName = "General Knowledge", SubCategoryName = "World Geography" },
    new GopreadyOnlineTest { CategoryName = "General Knowledge", SubCategoryName = "Inventions" },
    new GopreadyOnlineTest { CategoryName = "General Knowledge", SubCategoryName = "Honours and Awards" },
    new GopreadyOnlineTest { CategoryName = "Maths", SubCategoryName = "Time & Speed" },
    new GopreadyOnlineTest { CategoryName = "Maths", SubCategoryName = "Algebra" },
    new GopreadyOnlineTest { CategoryName = "Maths", SubCategoryName = "Accounts" }
};

让我们创建一个 ViewModel 来保存我们转换后的数据

public class SampleViewModel
{
    public string Category { get; set; }

    public List<string> SubCategories { get; set; }
}

那么你的动作应该是这样的:

[HttpGet]
public JsonResult GetOnlineTestTitle()
{               
    var result = search.GroupBy(x => x.CategoryName)
                       .Select(c => new SampleViewModel 
                                    { 
                                        Category = c.Key, 
                                        SubCategories = c.Select(sc => sc.SubCategoryName).Distinct().ToList() 
                                    });
    return Json(result, JsonRequestBehavior.AllowGet);
}

在前端,你的 javascript 应该是这样的:

function GetOnlineTestTitle() {    
    $.ajax({
        type: "GET",
        url: 'GetOnlineTestTitle',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: true,
        cache: false,
        success: function (msg) { 
            $("#examList").html("");
            var divs = msg.map(function (item) {
                var $div = $("<div>"); 
                var $ul = $("<ul>"); 
                var $h3 = $("<h3>").text(item.Category);

                item.SubCategories.forEach(function (itemSub) {
                    $ul.append($("<li>").text(itemSub));
                });
                $div.append($h3);
                $div.append($ul);
                return $div;
            });
            $('#examList').append(divs);
        },
        error: function (msg) {
            alert(JSON.stringify(msg));
        }
    });
}

你可以在这里看到它的工作原理:https://dotnetfiddle.net/PdaW67

由于上面的代码更具指导性,我在下面为您的案例添加了几乎真实的代码:

public ActionResult getOnlineTestTitle()
{
    var connectionString = WebConfigurationManager.ConnectionStrings["liveData"].ConnectionString;
    List<GopreadyOnlineTest> search = Session["OnlineTest"] as List<GopreadyOnlineTest> 
                                      ?? GopreadyOnlineTest.Search(connectionString).ToList();

    Session["OnlineTest"] = search;

    var result = search.GroupBy(x => x.CategoryName)
                       .Select(c => new SampleViewModel 
                                    { 
                                        Category = c.Key, 
                                        SubCategories = c.Select(sc => sc.SubCategoryName).Distinct().ToList() 
                                    });
    return Json(result, JsonRequestBehavior.AllowGet);            
}

【讨论】:

  • 感谢@Alberto Moteiro。你为我节省了很多时间。
  • @RaviKantHudda 很高兴能帮到你!!
  • 我仍然面临同样的问题。实际上我必须从数据库中获取数据。所以说基本常识有4条记录,所以重复4次。新的 GopredyOnlineTest { CategoryName = "General Knowledge", SubCategoryName = "Basic General Knowledge" }, new GopredyOnlineTest { CategoryName = "General Knowledge", SubCategoryName = "Basic General Knowledge" }, new GopredyOnlineTest { CategoryName = "General Knowledge", SubCategoryName = “基本常识”},
  • @RaviKantHudda 来自您的数据库的数据正确吗?
  • 是的,它来自数据库。但是,如果您能解决上述给定的问题,那对您来说就太好了。假设我的基本常识重复了 3 次,那么您的解决方案将如何解决问题。
猜你喜欢
  • 1970-01-01
  • 2023-04-10
  • 2011-02-02
  • 2011-04-01
  • 2021-10-29
  • 1970-01-01
  • 1970-01-01
  • 2013-03-31
  • 1970-01-01
相关资源
最近更新 更多