2012-01-24 51 views
1

考虑一个包含两个字段的表:FieldID和Position。位置是一个从1到4的字节。linq-to-sql基于ID列表的聚合计数

我正在写一个函数,它接收FieldID列表并返回linq-to-sql中每个位置中的项的计数。包含结果的对象有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个计数。你有什么建议。谢谢。

+0

您是否收到错误或错误的结果? – CodingGorilla

+0

@CodingGorilla:目前,我正在努力获取查询语法来生成结果。 – frenchie

回答

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(),使其更容易拾取值,以您所选择的模型转换成字典。

+0

我应该在过滤器中放入什么?其中t.Position = ???我的书单列表会发生什么?如何匹配表中的数据? – frenchie

+0

过滤器仅选择与您的列表匹配的数据。然后去分组。 –