views:

240

answers:

3

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.

+2  A: 

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.

Stephan
Thanks this works !!
Misnomer
A: 

Or .GroupBy(c => c.GoalId).AsQueryable()...

Stephen Cleary
Well, this still return an IGrouping item I do it like thisGroupBy(c => c.GoalId).AsQueryable().Tolist()but doing it as @Stephan way it works.
Misnomer
A: 

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();
Mark Byers
ya but will that in this case eliminate the entries..I want to group by as there are multiple entries for same GoalID.? I will try it out though thanks.
Misnomer
@VJ: OrderBy does not remove any results, it only changes the order.
Mark Byers