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

六眼飞鱼酱① 提交于 2019-12-12 11:23:25

问题


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.


回答1:


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.




回答2:


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();



回答3:


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



来源:https://stackoverflow.com/questions/2837220/how-to-perform-group-by-in-linq-and-get-a-iqueryable-or-a-custom-class-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!