LINQ with groupby and count

This is pretty simple but I’m at a loss:
Given this type of data set:

UserInfo(name, metric, day, other_metric)

and this sample data set:

joe  1 01/01/2011 5
jane 0 01/02/2011 9
john 2 01/03/2011 0
jim  3 01/04/2011 1
jean 1 01/05/2011 3
jill 2 01/06/2011 5
jeb  0 01/07/2011 3
jenn 0 01/08/2011 7

I’d like to retrieve a table that lists metrics in order(0,1,2,3..) with the total number of times the count occurs. So from this set, you’d end up with:

0 3    
1 2    
2 2    
3 1

I’m grappling with the LINQ syntax but am stuck on where to put a groupby and count…
any help?

POST Edit: I was never able to get the posted answers to work as they always returned one record with the number of different counts. However, I was able to put together a LINQ to SQL example that did work:

var pl = from r in info
         orderby r.metric    
         group r by r.metric into grp
         select new { key = grp.Key, cnt = grp.Count()};

This result gave me an ordered set of records with ‘metrics’ and the number of users associated with each. I’m clearly new to LINQ in general and to my untrained eye this approach seems very similar to the pure LINQ approach yet gave me a different answer.

3 Answers
3

Leave a Comment