David Létourneau
David Létourneau

Reputation: 1250

Group users by age for stats

first thing first my question is very similar to this one. In fact, it's the same thing, except that I need to group every user like this below:

  1. Everyone under 12 (exclusive)
  2. Then, from 12 - 19
  3. Then, from 20 - 29
  4. ...
  5. More than 80 (inclusive)

Based on the answer from dasblinkenlight in the other question, I was able to do:

var ageStats = vModel
                          .GroupBy(l => 10 * (l.Age / 10))
                          .OrderBy(x => x.Key)
                          .Select(g => new
                          {
                              Name = g.Key,
                              Count = g.Select(l => l.Age).Count()
                          }).ToList();

For a result set of :

  1. 0-9
  2. 10-19
  3. 20-29
  4. ...

So what should I do to accomplish the pattern I have to ?

Thank you very much !!

Upvotes: 1

Views: 173

Answers (3)

Mustafa ASAN
Mustafa ASAN

Reputation: 3825

var ages = new[] { 12, 19, 29, 80 };

var grouped = ages.Select(r => new {
                Name = r,
                Count = vModel.Count(x => x.Age >= r)
            });

Upvotes: 2

Martin K.
Martin K.

Reputation: 11

You could use approach mentioned here and use this code:

var ages = new List<int> { 12, 19, 29, 39, 49, 59, 69, 80, int.MaxValue};
var categories = vModel.GroupBy(item => ages.FirstOrDefault(ceil => ceil >= item));

Upvotes: 0

aspark
aspark

Reputation: 370

try this, but i don't know the performance

var ages = new int[12, 19, 29, 80];
var func = new Func<int, int>(a=>{

    for(var i = 0; i<ages.Length; i++){
        if(a<ages[i])
            continue;
        return i;
    }
    return 0;
});
vModel.GroupBy(m=>func(m.Age))....

Upvotes: 0

Related Questions