2012-01-24 86 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

過濾器僅選擇與您的列表匹配的數據。然後去分組。 –