2012-04-23 63 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) }; 
相关问题