2013-08-05 63 views
0

我需要使用linq動態分組列,即用戶將在運行時選擇表和列。如何在dataTable中使用多個列在c#中動態執行組操作?

enter image description here

例如:上表有領地,

國家,BANKNAME,

假設用戶已經選擇了這些列編組(領地,銀行名稱)

如何使用linq要做到這一點?

+0

動態'OrderBy'是不平凡的:http://stackoverflow.com/questions/41244/dynamic-linq-orderby- on-ienumerablet使用經典(弱類型)方法:'DataView dv = new DataView(table); dv.Sort =「State,BankName ASC」;' –

+0

存在一個名爲'DynamicQuery'的東西,我對分組沒有把握,但動態排序工作得很好。 https://www.nuget.org/packages/DynamicQuery – thmshd

回答

1

您可能需要使用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 
    } 
} 

檢查這個帖子Split a Datatable into multiple Datatables based on a list of column names

相關問題