linq-to-sql基于ID列表的聚合计数

时间:2012-01-24 19:29:48

标签: c# linq linq-to-sql

考虑一个包含两个字段的表:FieldID和Position。位置是一个字节,范围从1到4.

我正在编写一个接收FieldID列表的函数,并返回linq-to-sql中每个Positions中的项目数。包含结果的对象有4个字段,其中包含每个计数。

这就是我所拥有的:

public MyObjectModel GetCount(List<int>TheList)
{
   using (DC MyDC = new DC)
   {
     var Result = from t in MyDC.Table
                   where TheList.Select(i => i).Contains(t.FieldID)
                   select new MyObjectModel()
                   {
                      CountP1 = (from t in MyDC.Table
                                 where t.Position = 1
                                 where t.FieldID = ...).Count();

根据我收到的列表作为参数,我在计算问题时遇到了麻烦。我是以错误的方式接近这个吗?我想避免在4个不同的查询中单独查询每个计数,每个查询一个计数;我想在一次阅读中得到4个计数。你有什么建议。感谢。

1 个答案:

答案 0 :(得分:1)

为什么不首先按Position进行分组,然后在select中返回每个组的计数?

类似的东西:

var list = MyDC.Table
    .Where( your filter )
    .GroupBy( item => item.Position )
    .Select( g => new { pos = g.Key, count = g.Count() )
    .ToList();

// list contains items of type ( pos : int, count : int ) where pos is your Position    

您甚至可以将其转换为包含key = posval = count()的字典,以便更轻松地为您选择的模型选择值。