且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Linq计算组

更新时间:2023-02-10 14:36:18

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


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();

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