I have a Datatable result. I want to group by with some of the fields may be one or two or three. The main fact is developers can't know the numbers of fields clients want to group. So, for that case, I find some solutions about putting List parameters to group by fields. But can't find the proper one yet. Is there anybody who could help me with it? I was stuck with this issue for three days.
CodePudding user response:
Use reflection to dynamically group your DB-rows:
//something like:
var props = typeof(Foo).GetProperties().Where( x=> x.Name.Equals("MyField");
var result = rows.GroupBy( x => prop.GetValue( x ) );
For multiple fields, loop over them and apply the GroupBy to the result of the last iteration.
CodePudding user response:
I got it by using the groupby in Dynamic LinQ. Like this
var qfields = string.Join(",", stringarray.Select(x => "it[\"" x "\"] as " x));
var collVal = datatableresult.AsQueryable()
.GroupBy("new (" qfields ")", "it")
.Select("new (it.Key as Key,it as Data)");
This code group by the data table successfully but I still need to do the order by with multiple columns.