GroupBy和Sum

bre*_*iba 3 .net c# linq

我阅读了很多GroupBy + Sum主题,但我不明白如何使用它.

我有一个联系人列表,在这个列表中,我想得到状态(显示更多).

所以我的代码是:

contacts.GroupBy(i => i.Address.State.ToUpperInvariant());
Run Code Online (Sandbox Code Playgroud)

在这个GroupBy中,我想知道更多的状态(并删除""的情况,因为空状态对我来说并不重要).

我该怎么做?

我在考虑这样的事情:

contacts.GroupBy(i => i.Address.State.ToUpperInvariant()).Select(i => i.Max());
Run Code Online (Sandbox Code Playgroud)

提前致谢!

Lee*_*Lee 6

你想要的东西:

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());
Run Code Online (Sandbox Code Playgroud)

GroupBy返回一个IEnumerable<IGrouping<TKey, TSource>>.自IGrouping <TKey,TSource>实现以来IEnumerable<TSource>,您可以使用Count扩展方法来获取组中元素的数量.