2012-04-23 37 views
3

我已經使用這個Linq查詢如何獲得的數據和使用多列列表值

filterEntities = (from list in filterEntities where list.Id== 0 && list.Id== 1 && list.Id == 3 && list.Id== 6 select list).OrderBy(r => r.Id).ToList(); 

現在這個LINQ返回類似

ID Age 
0 18 
0 19 
1 21 
3 24 
6 32 
6 08 

我要生成一個列表的列表使用同一ID的總和,它返回像

ID Age 
0 37 
1 21 
3 24 
6 40 

列表請建議我可以查詢

+0

在Sql,這是'GroupBy'。 – Oliver 2012-04-23 13:17:11

+3

該列表如何返回任何值? Id列如何爲0和1以及3和6?你的意思是寫OR(||)嗎? – RoelF 2012-04-23 13:22:55

回答

4

我認爲你是希望通過這樣的

List<int> ids = new List<int>() { 0, 1, 3, 6 }; 

filterEntities = (from list in filterEntities 
        where ids.Contains(list.Id) 
        group list by list.id into g 
        orderby g.Key 
        select new 
        { 
        ID = g.Key, 
        Age = g.Sum(x => x.Age), 
        }).ToList(); 
0
filterEntities = filterEntities.Where(l=>new[] { 0, 1, 3, 6 }.Contains(l.Id)) 
           .Sum(c=>c.Age) 
           .GroupBy(r=>r.Id)         
           .ToList(); 
1

我會收拾這樣的查詢使用一組,因爲長表達式看起來有點混亂:

var idList = new List<int> { 0, 1, 3, 6}; 

filterEntities = from e in filterEntities 
       where idList.Contains(e.Id) 
       group e by e.Id into g 
       select new { Id = g.Key, Sum = g.Sum(e =>e.Age) };