如何在C#中实现linq on dictionary?

Rav*_*dda 2 c# linq jquery dictionary razor

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

基本知识

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

数学

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

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

基本知识

  • 基础常识
  • 基础常识
  • 基础常识

根据每个子类别的问题数量重复这一过程.

我正在使用的代码是

 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);            
    }
Run Code Online (Sandbox Code Playgroud)

这是我的proc,它将数据返回给我.

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)

     ----------
Run Code Online (Sandbox Code Playgroud)

请解决此问题.如果我放下以下行来解决问题,那就不允许我这样做.

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

这是我的动态设计页面的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));
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

Alb*_*iro 6

您可以使用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; }
}
Run Code Online (Sandbox Code Playgroud)

并且您的List<GopreadyOnlineTest> 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" }
};
Run Code Online (Sandbox Code Playgroud)

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

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

    public List<string> SubCategories { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后你的行动应该是这样的:

[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);
}
Run Code Online (Sandbox Code Playgroud)

在前端,你的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));
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

你可以在这里看到它: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);            
}
Run Code Online (Sandbox Code Playgroud)