Ian Vink
Ian Vink

Reputation: 68740

Linq: Totals Groups By Month

I have a simple business object:

Crime 
     Date
     PersonsInvolved

I need a list of total PersonsInvolved per month. The data is for 1 year so year doesn't need to be taken into account.

Jan 5
Feb 3
Mar 5

and so on

How is this done in Linq if I have an in memory collection like this:

List<Crime>() crimes;

Upvotes: 3

Views: 10440

Answers (3)

codekaizen
codekaizen

Reputation: 27419

crimes.GroupBy(c => c.Date.Month)
      .Select(g => new { Month = g.Key, Count = g.Count() });

Upvotes: 11

JMarsch
JMarsch

Reputation: 21753


var q =  from i in crimes
    group i by i.Date.ToString("MMM") into grp
    select new {Month = grp.Key, Count = grp.Sum(i => i.Persons)};

Upvotes: 5

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

List<Crime>() crimes = ...
var crimesPerMonth = crimes.GroupBy(x => x.Date.Month);

Upvotes: 0

Related Questions