3

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!

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.