How to get the sum of data in a list using multiple column values

I have a list using this Linq query

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();

Now this linq returns a list, for example

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

I want to generate a list using the sum of the same identifier, which is returned as

ID  Age
0    37
1    21
3    24
6    40

Please offer me a possible request.

+3
source share
3 answers

I think you want to use a group like this

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();
+4
source

I would clear the query like this because the long expression looks a bit confusing:

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) };
+1
source
filterEntities =  filterEntities.Where(l=>new[] { 0, 1, 3, 6 }.Contains(l.Id))
                                .Sum(c=>c.Age)
                                .GroupBy(r=>r.Id)                                   
                                .ToList();
0
source

All Articles