0

I need to group columns using linq dynamically i.e. user will select table and columns at runtime.

enter image description here

Ex: The above table has Territory,

State, BankName,

Assume user has selected these columns for grouping (Territory,Bank Name)

How can use linq to do this?

Ranjith kumar
  • 223
  • 2
  • 6
  • 11
  • Dynamic `OrderBy` is not trivial: http://stackoverflow.com/questions/41244/dynamic-linq-orderby-on-ienumerablet With classic ( weakly typed ) methods: `DataView dv = new DataView(table); dv.Sort = "State, BankName ASC";` – Tim Schmelter Aug 05 '13 at 13:46
  • There exists something called `DynamicQuery`, I'm nore sure about Grouping, but dynamic sorting works pretty well. https://www.nuget.org/packages/DynamicQuery – thmshd Aug 05 '13 at 13:59

1 Answers1

1

you may want to use System.Linq.Dynamic

var fields = new List<string>() { "Territory", "Bank Name"};
var qfields = string.Join(", ", fields.Select(x => "it[\"" + x + "\"] as " + x));

var q = dt
    .AsEnumerable()
    .AsQueryable()
    .GroupBy("new(" + qfields + ")", "it")
    .Select("new (it as Data)");
foreach (dynamic d in q)
{
    foreach (var row in d.Data)
    {
       // Do your work here, using d.Territory
    }  
}

Check this post Split a Datatable into multiple Datatables based on a list of column names

Community
  • 1
  • 1
Roman Pekar
  • 107,110
  • 28
  • 195
  • 197