Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting Using Group By Linq

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(); 
like image 419
Nick LaMarca Avatar asked Sep 04 '12 19:09

Nick LaMarca


People also ask

How does group by work in Linq?

Group by works by taking whatever you are grouping and putting it into a collection of items that match the key you specify in your group by clause.

Does Linq Group by keep order?

Found answer on MSDN: Yes.


1 Answers

var noticesGrouped = notices.GroupBy(n => n.Name).                      Select(group =>                          new                          {                              NoticeName = group.Key,                              Notices = group.ToList(),                              Count = group.Count()                          }); 
like image 198
Leniel Maccaferri Avatar answered Sep 21 '22 13:09

Leniel Maccaferri