Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform group by in LINQ and get a Iqueryable or a Custom Class Object?

Here is my query -

var data = Goaldata.GroupBy(c => c.GoalId).ToList();

This returns a Igrouping object and I want an Iqueryable object which I can directly query to get the data while in this case I have to loop through using a foreach() and then get the data. Is there another way to group by in LINQ which returns directly as a list of Iqueryable or a List as similar to what happens for order by in LINQ.

like image 402
Vishal Avatar asked Dec 04 '22 12:12

Vishal


2 Answers

The easiest way is probably

var data = Goaldata.GroupBy(c => c.GoalId).SelectMany(c => c).ToList();

In the OO sense they aren't really grouped, but they are ordered with the groups together.

like image 139
Stephan Avatar answered Jan 04 '23 23:01

Stephan


Whilst the accepted answer is correct, it seems to be unnecessarily complicated. Assuming GoalId is an int you can just use OrderBy:

var data = Goaldata.OrderBy(c => c.GoalId).ToList();
like image 44
Mark Byers Avatar answered Jan 05 '23 01:01

Mark Byers