在linq-to-sql中分组和计数

时间:2012-01-27 14:58:48

标签: c# linq linq-to-sql

我有以下查询接收ID列表,我想进行计数。还有一个对象模型CountModel,它保存计数,每个属性定义为一个int。

public class GetCountByStatus(List<int> TheIDs)
{
 ...using MyDC...
 var CountData = (from d in MyDC.Data
                  where TheIDs.Contains(d.ID)
                  group d by d.Status into statusgroup
                  select new CountModel()
                  { 
                     CountStatus1 = (from g in statusgroup
                                     where g.Status == 1
                                     select g).Count(),

                     CountStatus2 = (from g in statusgroup
                                     where g.Status == 2
                                     select g).Count(),

                     CountStatusN = ....

                   }).Single();

例如,如果没有状态为N的元素,那么此代码会崩溃还是CountStatusN的计数为0?这是做我想做的最好的方式吗?

感谢。

2 个答案:

答案 0 :(得分:2)

我会选择一本字典,尝试这样的事情:

var countData = MyDC.Data.Where(y => TheIDs.Contains(y.ID))
    .GroupBy(y => y.Status).ToDictionary(y => y.Key, y => y.Count());

我没有尝试过自己,也没有在VS中编写代码,但我认为这几乎就是你能做到的。这将为您提供一个字典,其中键是状态,值是该状态的计数。

定义名为SomethingX的属性的模型不是很灵活。这意味着当有新状态时,您必须更改模型。将数据保存在字典中可以避免这种情况。

答案 1 :(得分:1)

Count()将始终返回一个整数,如果没有具有给定状态的元素,则为0。因此CountStatusN也将是一个整数。

相关问题