我有一个使用此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 :(得分: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();
答案 1 :(得分: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) };
答案 2 :(得分:0)
filterEntities = filterEntities.Where(l=>new[] { 0, 1, 3, 6 }.Contains(l.Id))
.Sum(c=>c.Age)
.GroupBy(r=>r.Id)
.ToList();