如何在C#中实现字典上的linq?
在C#中使用linq on dictionary创建在线考试门户时,我遇到了一个问题。我关心的是获取在线考试类别、子类别。我向数据库服务器请求获取我的数据。现在,我的数据在前端可用,但我正在尝试以一种方便的方式获取记录,以便我可以将我的数据划分为类别、子类别和问题。例如,我希望我的标题和类别如下:- 一般知识如何在C#中实现字典上的linq?,c#,jquery,linq,dictionary,razor,C#,Jquery,Linq,Dictionary,Razor,在C#中使用linq on dictionary创建在线考试门户时,我遇到了一个问题。我关心的是获取在线考试类别、子类别。我向数据库服务器请求获取我的数据。现在,我的数据在前端可用,但我正在尝试以一种方便的方式获取记录,以便我可以将我的数据划分为类别、子类别和问题。例如,我希望我的标题和类别如下:- 一般知识 基本常识 世界地理 发明 荣誉和奖励 数学 时间与速度 代数学 帐目 但下面给出的代码显示了我的结果 一般知识 基本常识 基本常识 基本常识 这是根据每个子类别的问题数量重复的
- 基本常识
- 世界地理
- 发明
- 荣誉和奖励
- 时间与速度
- 代数学
- 帐目
- 基本常识
- 基本常识
- 基本常识
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);
}
请帮忙解决这个问题。如果我用下面这句话来解决这个问题,它是不允许我这样做的
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));
}
});
}
函数GetOnlineTestTitle(){
$.ajax({
键入:“获取”,
url:“getOnlineTestTitle”,
contentType:“应用程序/json;字符集=utf-8”,
数据类型:“json”,
async:true,
cache:false,
成功:函数(msg){
var htmlString='';
警报(JSON.stringify(msg));
$(“#examList”).html(htmlString);
$。每个(消息、函数(键、值){
如果(值长度!=0){
htmlString+=''+key+' ';
}
$.each(val,function)(键2,val2){
htmlString+='';
});
});
$('#examList').append(htmlString);
},
错误:函数(msg){
警报(“错误:+JSON.stringify(msg));
}
});
}
您可以使用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; }
}
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" }
};
[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);
}
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));
}
});
}
您的列表搜索变量包含如下数据:
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; }
}
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" }
};
[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);
}
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));
}
});
}
在前端,您的javascript应该是这样的:
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; }
}
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" }
};
[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);
}
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));
}
});
}
函数GetOnlineTestTitle(){
$.ajax({
键入:“获取”,
url:'GetOnlineTestTitle',
contentType:“应用程序/json;字符集=utf-8”,
数据类型:“json”,
async:true,
cache:false,
成功:函数(msg){
$(“#examList”).html(“”);
var divs=msg.map(函数(项){
变量$div=$(“”);
var$ul=$(“”);
var$h3=$(“”).text(item.Category);
item.SubCategories.forEach(功能(itemSub){
$ul.append($(“- ”).text(itemSub));
});
$div.append($h3);
$div.append($ul);
返回$div;
});
$('examList')。追加(divs);
},
错误:函数(msg){
警报(JSON.stringify(msg));
}
});
}
您可以看到它在这里工作:
由于上面的代码更具说教性,我为您的案例添加了以下几乎真实的代码:
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);
}
公共操作结果getOnlineTestTitle()
{
var connectionString=WebConfiguration Manager.connectionString[“liveData”]。connectionString;
列表搜索=会话[“OnlineTest”]作为列表
??GopreadyOnlineTest.Search(connectionString.ToList();
会话[“OnlineTest”]=搜索;
var result=search.GroupBy(x=>x.CategoryName)
.选择(c=>new SampleViewModel
{
类别=c键,
SubCategories=c.Select(sc=>sc.subcategorityname).Distinct().ToList()
});
返回Json(结果,JsonRequestBehavior.AllowGet);
}
I gess你应该使用GroupBy
我也试过了。但是没有成功。:-)你能发布你的视图显示类别吗?我也面临同样的问题。@kcwu我正在使用ajax调用设计布局。谢谢@Alberto Moteiro。你为我节省了很多时间。@RaviKantHudda我很高兴能帮助你!!我仍然面临同样的问题。实际上,我必须从数据库中获取数据。假设基本常识有4条记录,这是重复4次。新GOPREADYONLINEST{CategoryName=“General Knowledge”,SubCategoryName=“Basic General Knowledge”},新GOPREADYONLINEST{CategoryName=“General Knowledge”,SubCategoryName=“Basic General Knowledge”},新GOPREADYONLINEST{CategoryName=“General Knowledge”,SubCategoryName=“基本常识”},@RaviKantHudda是从您的数据库提交的数据,对吗?是的,它来自数据库。但如果您能解决上述给定的问题,那对您来说太好了。假设我将基本常识重复3次,那么您的解决方案将如何解决问题。