Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

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 like

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

I want to generate a list using sum of same Id's which returns like

ID  Age
0    37
1    21
3    24
6    40

Please suggest me possible query

like image 213
Haseeb Akhtar Avatar asked Nov 30 '25 16:11

Haseeb Akhtar


2 Answers

I think you are looking to use a group by 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();
like image 177
Aducci Avatar answered Dec 02 '25 06:12

Aducci


I would clean up 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) };
like image 25
RoelF Avatar answered Dec 02 '25 05:12

RoelF



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!