How to use GroupBy using Dynamic LINQ

亡梦爱人 提交于 2019-11-27 23:50:14

There is default it defined, you can use it to return matched elements:

var mydataGrouped = mydata.GroupBy("Shop", "it");  

To iterate through results you should additionally Select elements to name it and use dynamics:

var mydataGrouped = mydata.GroupBy("Shop", "it").Select("new (it.Key as Shop, it as Albums)");

foreach (dynamic group in mydataGrouped)
{
   foreach (dynamic album in group.Albums)
   {
      Console.WriteLine(album.Author);
   }
}

You may construct the group by expression dynamically or give a try to this Dynamic LINQ library presented on ScottGu's page:
http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

This is the method I have copied from DynamicQuery:

public static IQueryable GroupBy(this IQueryable source, string keySelector, string elementSelector, params object[] values) {..}

In my example I provide the keySelector and the elementSelector.

listAlbums.AsQueryable().GroupBy("it.Shop", "it").Select("Author"); You can use new with GroupBy or with select for the new types.

It like this in OOP class.

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