How to use GroupBy using Dynamic LINQ

后端 未结 3 1976
清歌不尽
清歌不尽 2020-12-03 10:59

I am trying to do a GroupBy using Dynamic LINQ but have trouble getting it to work.

This is some sample code illustrating the problem:

List

        
相关标签:
3条回答
  • 2020-12-03 11:37

    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);
       }
    }
    
    0 讨论(0)
  • 2020-12-03 11:56

    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

    0 讨论(0)
  • 2020-12-03 11:56

    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.

    0 讨论(0)
提交回复
热议问题