【发布时间】: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