Home > Software design >  Linq group by and select sum
Linq group by and select sum

Time:11-25

I currently have 2 lists, one is records, one is for cards. I'm trying to join these two lists on a shared GUID, then group by the name of the card to find the total quantity of cards with that name. I'm just not sure how to get this group by statement to work, does anyone have any ideas?

            var values = (from r in records
                      join c in cards
                      on r.CardGUID equals c.GUID
                      orderby c.Name ascending
                      select new
                      {
                          Name = c.Name,
                          Quantity = r.Quantity
                      })
                      .GroupBy(e => new { e.Name });

CodePudding user response:

If you want to calculate the sum of quantities within each group you would add something like this after your groupBy:

.Select(group => new {group.Key, group.Sum(g => g.Quantity)});

I.e. for each group you create a new object, with the key/name and the sum of quantities for that group.

  • Related