[英]linq group by with c#
I have made a method in my Models class to call set of data from data base by below codes: 我在Models类中创建了一个方法,可以通过以下代码从数据库中调用数据集:
public IQueryable result(string username, string exam)
{
return (from result in idb.User_Exam_Question
where (result.User_Tbl_email == username && result.Exam_Tbl_ID == Convert.ToInt32(exam))
group result by result.category_tbl_ID into cat
select cat);
}
but I need to count the rows of each category . 但是我需要计算每个类别的行数。 how should I change the above code to get my desirable output .
我应该如何更改上面的代码以获得我想要的输出。
many thanks 非常感谢
If you want to return the count, just add .Count()
: 如果要返回计数,只需添加
.Count()
:
public int result(string username, string exam)
{
return (from result in idb.User_Exam_Question
where (result.User_Tbl_email == username && result.Exam_Tbl_ID == Convert.ToInt32(exam))
group result by result.category_tbl_ID into cat
select cat).Count();
}
Or, if you want each sub-result as a count, you can do this: 或者,如果您希望将每个子结果都作为一个计数,则可以执行以下操作:
public IQueryable result(string username, string exam)
{
return from result in idb.User_Exam_Question
where (result.User_Tbl_email == username && result.Exam_Tbl_ID == Convert.ToInt32(exam))
group result by result.category_tbl_ID into cat
select new
{
CatCount = cat.Count()
}
}
You can then do something like this: 然后,您可以执行以下操作:
result("username", "exam")[0].CatCount;
// returns the count of the first result of the query.
You can get the count directly from your cat ! 您可以直接从猫那里得到计数!
public IQueryable result(string username, string exam)
{
return (from result in idb.User_Exam_Question
where (result.User_Tbl_email == username && result.Exam_Tbl_ID == Convert.ToInt32(exam))
group result by result.category_tbl_ID into cat
select new { Group = cat , Count = cat.Count() } );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.