C# 使用 Group By Linq 进行计数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12270018/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 22:42:19  来源:igfitidea点击:

Counting Using Group By Linq

c#linqcountgroup-bydistinct

提问by Nick LaMarca

I have an object that looks like this:

我有一个看起来像这样的对象:

Notice 
{
    string Name,
    string Address 
}

In a List<Notice>I want to output All distinct Name and how many times the particular appears in the collection.

List<Notice>我想输出所有不同的名称以及特定在集合中出现的次数。

For example:

例如:

Notice1.Name="Travel"
Notice2.Name="Travel"
Notice3.Name="PTO"
Notice4.Name="Direct"

I want the output

我想要输出

Travel - 2
PTO - 1
Direct -1

I can get the distinct names fine with this code but I can't seem to get the counts all in 1 linq statement

我可以使用此代码获得不同的名称,但似乎无法在 1 条 linq 语句中获得所有计数

  theNoticeNames= theData.Notices.Select(c => c.ApplicationName).Distinct().ToList();

采纳答案by Leniel Maccaferri

var noticesGrouped = notices.GroupBy(n => n.Name).
                     Select(group =>
                         new
                         {
                             NoticeName = group.Key,
                             Notices = group.ToList(),
                             Count = group.Count()
                         });

回答by Jon Skeet

A variation on Leniel's answer, using a different overload of GroupBy:

Leniel 答案的变体,使用了不同的重载GroupBy

var query = notices.GroupBy(n => n.Name, 
                (key, values) => new { Notice = key, Count = values.Count() });

Basically it just elides the Selectcall.

基本上它只是忽略了Select调用。