简体   繁体   English

如何在C#中的字典上实现linq?

[英]How to Implement linq on dictionary in C#?

I am facing a problem while creating online exam portal using linq on dictionary in C#. 我在C#中的字典上使用linq创建在线考试门户时遇到问题。 My concern is to get Online Exam category, SubCategory. 我关心的是获得在线考试类别SubCategory。 I made a request to database server to fetch my data. 我向数据库服务器发出了获取数据的请求。 Now my data is available at front end but I am trying to fetch record in a convenient way so that I can divide my data in Category, Subcategory and questions. 现在我的数据可以在前端使用,但是我试图以一种方便的方式获取记录,以便可以将我的数据划分为“类别”,“子类别”和“问题”。 for example I want my Headline and category to be like:- 例如,我希望我的标题和类别为:-

General Knowledge 基本知识

  • Basic General Knowledge 基本常识
  • World Geography 世界地理
  • Inventions 发明
  • Honours and Awards 荣誉与奖项

Maths 数学

  • Time & Speed 时间与速度
  • Algebra 代数
  • Accounts 帐号

but with below given code my result is being displayed 但是用下面的给定代码显示我的结果

General Knowledge 基本知识

  • Basic General Knowledge 基本常识
  • Basic General Knowledge 基本常识
  • Basic General Knowledge 基本常识

this is getting repeated according to the number of question per subcategory. 根据每个子类别的问题数量,这种情况越来越多。

Code I am using is 我正在使用的代码是

 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);            
    }

Here is my proc which is returning me the data. 这是我的程序,正在向我返回数据。

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)

     ----------

Please help by solving this. 请解决此问题。 If I put following line to solve the problem it is not allowing me to do this. 如果我遵循以下思路来解决问题,那是不允许我这样做的。

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

Here is my jquery which is designing the page dynamically. 这是我的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));
        }
    });
}

You can use GroupBy method from LINQ to do that, see below. 您可以使用LINQ的GroupBy方法来执行此操作,请参见下文。

Assuming that your GopreadyOnlineTest class is like that: 假设您的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; }
}

And your List<GopreadyOnlineTest> search variable contains some data like that: 并且您的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" }
};

Lets create a ViewModel to hold our transformed data 让我们创建一个ViewModel来保存我们的转换数据

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

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

Then your action should be like that: 然后,您的操作应如下所示:

[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);
}

And in front end, your javascript should be like that: 在前端,您的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));
        }
    });
}

You can see it working here: https://dotnetfiddle.net/PdaW67 您可以在这里看到它的工作: https : //dotnetfiddle.net/PdaW67

Since the code above is more didatic, I am adding below almost real code for your case: 由于上面的代码更具说服力,因此我在下面为您的案例添加了几乎真实的代码:

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);            
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM