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

请建议我可能的查询

4

3 回答 3

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();
于 2012-04-23T13:21:00.080 回答
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) };
于 2012-04-23T13:26:25.367 回答
0
filterEntities =  filterEntities.Where(l=>new[] { 0, 1, 3, 6 }.Contains(l.Id))
                                .Sum(c=>c.Age)
                                .GroupBy(r=>r.Id)                                   
                                .ToList();
于 2012-04-23T13:20:04.990 回答