Counting Using Group By Linq

好久不见. 提交于 2019-12-04 09:06:57

问题


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.

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

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

回答1:


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



回答2:


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

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

Basically it just elides the Select call.



来源:https://stackoverflow.com/questions/12270018/counting-using-group-by-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!