Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GroupBy and Sum

Tags:

c#

.net

linq

I read a lot of GroupBy + Sum topics but I didn't understand how to use it.

I have a list of contacts, and in this list, i want to get the state (which appears more).

So my code is:

contacts.GroupBy(i => i.Address.State.ToUpperInvariant());

In this GroupBy, I want to know the state that appears more (and remove the case of "" because empty state is not important to me).

How do I do it?

I was thinking in something like this:

contacts.GroupBy(i => i.Address.State.ToUpperInvariant()).Select(i => i.Max());

Thanks in advance!

like image 991
briba Avatar asked Dec 17 '25 15:12

briba


1 Answers

You want something like:

var counts = contacts
    .Where(c => c.State != string.Empty)
    .GroupBy(i => i.Address.State, StringComparer.OrdinalIgnoreCase)
    .Select(grp => new { State = grp.Key, Count = grp.Count());

GroupBy returns an IEnumerable<IGrouping<TKey, TSource>>. Since IGrouping<TKey, TSource> implements IEnumerable<TSource>, you can use the Count extension method to get the number of elements in the group.

like image 84
Lee Avatar answered Dec 19 '25 04:12

Lee



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!