Reputation: 513
var query = from i in listModel
group i by new { i.ClassId, i.Gender } into g
orderby g.Key.ClassId, g.Key.Gender
from item in g
select new
{
g.Key.ClassId,
g.Key.Gender,
item.Name,
Count = g.Count(),
MaxAge = g.Max(i => i.Age),
MinAge = g.Min(i => i.Age)
};
Using this code, I can find out the aggregated value (Count, MaxAge, MinAge) and the detailed value (Name) before grouping at the same time. How can the above statement be implemented by Linq's Lambda expression?
Upvotes: 0
Views: 207
Reputation: 23228
Try the conjunction of GroupBy
, OrderBy
and SelectMany
extension methods
var query = listModel.GroupBy(i => new { i.ClassId, i.Gender })
.OrderBy(g => g.Key.ClassId)
.ThenBy(g => g.Key.Gender)
.SelectMany(g => g, (g, item) => new
{
g.Key.ClassId,
g.Key.Gender,
item.Name,
Count = g.Count(),
MaxAge = g.Max(i => i.Age),
MinAge = g.Min(i => i.Age)
});
Upvotes: 1