2014-09-22 50 views
0

我有一個包含人名和年齡等數據庫。我有一個查詢,按名稱分組,並獲得與標準匹配的每個名稱的數量。 ListHelper類型只是一個包含這兩個屬性的類。如何獲得linq計數結果的總和

IEnumerable<ListHelper> HelperEnumerable = null 
HelperEnumerable = _repository.Persons 
     .Where(b => b.Age < 18) 
      .GroupBy(
        n => n.FirstName 
        , a => a.FirstName 
        , (key, count) => new ListHelper { Name = key, Amount = count.Count() } 
        ); 

當我ToList()的HelperEnumerable結果是這樣的: 名稱: 「邁克爾」,金額:100, 名稱: 「EVA」,金額:122, 名稱: 「莉莎」,金額: 71, 等

我怎樣才能得到類似的結果,但與這樣的結果符合條件的所有人員數: 名稱:「全部」,金額:17280

我想有鍵值對,所有其他代碼可以保持不變,只有這一點查詢將返回所有matchig行的計數,而不是由任何特定的columm分組。

我已經試過這僅返回詮釋計數:

HelperEnumerable = _repository.Persons 
      .Where(b => b.Age < 18).Count(); 

和計數(後我無法添加

.Select(a => (key,count) new ListHelper{ key = "All", count = a }) 

)嘗試來推算結果有兩個領域。

回答

1

是什麼:

IEnumerable<ListHelper> HelperEnumerable = null 
HelperEnumerable = _repository.Persons 
     .Where(b => b.Age < 18) 
      .GroupBy(
        n => "All" 
        , (key, count) => new ListHelper { Name = key, Amount = count.Count() } 
        ); 

這樣做,你需要它做什麼?

或者爲什麼不乾脆:

new ListHelper{ key = "All", count = _repository.Persons.Where(b => b.Age < 18).Count() }; 

+0

謝謝@tolanj,那真的做了我需要它做的事情。我想我只是太困惑了,沒有嘗試過這個明顯的解決方案:) – Lupa 2014-09-23 15:39:35