Nic*_*rca 31 c# linq group-by count distinct
我有一个看起来像这样的对象:
Notice
{
string Name,
string Address
}
Run Code Online (Sandbox Code Playgroud)
在List<Notice>我想要输出所有不同的名称和特定在集合中出现的次数.
例如:
Notice1.Name="Travel"
Notice2.Name="Travel"
Notice3.Name="PTO"
Notice4.Name="Direct"
Run Code Online (Sandbox Code Playgroud)
我想要输出
Travel - 2
PTO - 1
Direct -1
Run Code Online (Sandbox Code Playgroud)
我可以使用此代码获得不同的名称,但我似乎无法在1个linq语句中获得所有计数
theNoticeNames= theData.Notices.Select(c => c.ApplicationName).Distinct().ToList();
Run Code Online (Sandbox Code Playgroud)
Len*_*rri 56
var noticesGrouped = notices.GroupBy(n => n.Name).
Select(group =>
new
{
NoticeName = group.Key,
Notices = group.ToList(),
Count = group.Count()
});
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 48
Leniel答案的变体,使用不同的重载GroupBy:
var query = notices.GroupBy(n => n.Name,
(key, values) => new { Notice = key, Count = values.Count() });
Run Code Online (Sandbox Code Playgroud)
基本上它只是省略了Select电话.