Seems this is an issue that multiple people have asked around at several occasions.
The question is how to use a Linq query where you want to group on more than one ‘field’
Turns out it is really not that hard. Thanks to ‘Anonymous’ methods that was also introduced ‘yay back’ it is as simple as the following example. Lets say you have a list of values like these:
Person 1: Age = 25, Gender = M, HighScore = 123
Person 2: Age = 21, Gender = F, HighScore = 99
Person 3: Age = 27, Gender = M, HighScore = 140
Person 4: Age = 19, Gender = M, HighScore = 131
Person 5: Age = 25, Gender = M, HighScore = 119
Person 6: Age = 22, Gender = M, HighScore = 108
Person 7: Age = 27, Gender = M, HighScore = 152
Person 8: Age = 21, Gender = M, HighScore = 98
Person 9: Age = 22, Gender = M, HighScore = 101
Person 10: Age = 25, Gender = M, HighScore = 167
Person 11: Age = 22, Gender = F, HighScore = 105
… etc
To get a simple report on average high score by Age and Gender you’ll have to use a query like this:
foreach(var entry in (from p in Persons
group p by new { Age = p.Age, Gender = p.Gender } into g
orderby g.Key.Age, g.Key.Gender
select new
{
Age = g.Key.Age,
Gender = g.Key.Gender,
Avg = g.Average(pavg=>p.HighScore)
} )){
Console.WriteLine(“Age: {0}, Gender: {1}, Avg: {2}”, entry.Age, entry.Gender, entry.Avg);
}
Perhaps it might have simpler if you could simply have stated : “group p by p.Age, p.Gender” but unfortunately this is not supported. Then again this allows you to be more creative in defining the anonymous type so you can manipulate the data even more. Perhaps in the next version of Linq… if there is ever one…
0 Comments.