2013-10-21 71 views
2

任何人都可以幫助我獲得這項工作嗎?Groupby使用動態LINQ

我有以下代碼:

dt.Columns.Add("Field1", typeof(String)); 
dt.Columns.Add("Field2", typeof(String)); 
dt.Columns.Add("NR", typeof(Double)); 

dt.Rows.Add("A", "990001", 100); 
dt.Rows.Add("A", "990001", 120); 
dt.Rows.Add("B", "990001", 200); 
dt.Rows.Add("B", "990001", 300); 

var fields = new List<string>() { "Field1", "Field2" }; 

var q = dt.AsEnumerable().AsQueryable() 
      .GroupBy("new(" + qfields + ")", "it") 
      .Select("new(Key as Group, Sum(NR) as Tot)"); 

當我執行這個代碼中,我得到的錯誤:

No property or field 'NR' exists in type 'DataRow'

我需要的結果爲:

A, 990001, 220 
B, 990001, 500 

回答

1
var q = 
    dt.AsEnumerable() 
     .AsQueryable() 
     .GroupBy("new(it[\"Field1\"] as Field1,it[\"Field2\"]as Field2)", "it") 
     .Select("new(Key as Group, Sum(double(it[\"NR\"])) as Tot)"); 
foreach (var v in q) 
{ 
    Console.WriteLine(v); 
}