Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Linq Groupby SELECT Key, List<T>

Tags:

c#

linq

I am using Dynamic Linq helper for grouping data. My code is as follows :

Employee[] empList = new Employee[6];
empList[0] = new Employee() { Name = "CA", State = "A", Department = "xyz" };
empList[1] = new Employee() { Name = "ZP", State = "B", Department = "xyz" };
empList[2] = new Employee() { Name = "AC", State = "B", Department = "xyz" };
empList[3] = new Employee() { Name = "AA", State = "A", Department = "xyz" };
empList[4] = new Employee() { Name = "A2", State = "A", Department = "pqr" };
empList[5] = new Employee() { Name = "BA", State = "B", Department = "pqr" };

var empqueryable = empList.AsQueryable();
var dynamiclinqquery  = DynamicQueryable.GroupBy(empqueryable, "new (State, Department)", "it");

How can I get back the Key and corresponding list of grouped items i.e IEnumerable of {Key, List} from dynamiclinqquery ?

like image 918
ideafountain Avatar asked Feb 20 '23 04:02

ideafountain


1 Answers

I solved the problem by defining a selector that projects the Key as well as Employees List.

       var eq = empqueryable.GroupBy("new (State, Department)", "it").Select("new(it.Key as Key, it as Employees)");
       var keyEmplist = (from dynamic dat in eq select dat).ToList();

       foreach (var group in keyEmplist)
       {
           var key = group.Key;
           var elist = group.Employees;

           foreach (var emp in elist)
           {

           }                                          
       }
like image 121
ideafountain Avatar answered Feb 21 '23 17:02

ideafountain