2015-10-06 100 views
1

我有的DataTable類型的三個表:LINQ:加入3個數據表,並添加計算字段

Table1: Id<Int64>, ParamX<string>; 
Table2: Id<Int64>; 
Table3: Id<Int64>, ParamA<double>, ParamB<Int16>; 

我想通過ID字段加入他們的行列,並創建與表4計算字段ParamC<double>=ParamA<double>*ParamB<Int16>

結果應該是數據表

Table4: Id<Int64>, ParamX<string>, ParamA<double>, ParamB<Int16>, ParamC<double> 

是否有可能使它在單個LINQ查詢? madace

+0

datatable或Linq? – andy

回答

2

您不能在LINQ查詢中創建或填充表,查詢不應導致副作用。你可以準備數據要插入到新表使用LINQ:

var query = from r1 in Table1.AsEnumerable() 
      join r2 in Table2.AsEnumerable() 
      on r1.Field<long>("ID") equals r2.Field<long>("ID") 
      join r3 in Table3.AsEnumerable() 
      on r2.Field<long>("ID") equals r3.Field<long>("ID") 
      select new { 
       ID = r1.Field<long>("ID"), 
       ParamX = r1.Field<string>("ParamX"), 
       ParamA = r3.Field<double>("ParamA"), 
       ParamB = r3.Field<short>("ParamB"), 
       ParamC = r3.Field<double>("ParamA") * r3.Field<short>("ParamB") 
      }; 

var Table4 = new DataTable(); 
Table4.Columns.Add("ID", typeof(long)); 
Table4.Columns.Add("ParamX", typeof(string)); 
Table4.Columns.Add("ParamA", typeof(double)); 
Table4.Columns.Add("ParamB", typeof(short)); 
Table4.Columns.Add("ParamC", typeof(double)); 

您可以使用一個循環來執行查詢,並於行插入到表:

foreach (var x in query) 
{ 
    DataRow addedRow = Table4.Rows.Add(); 
    addedRow.SetField("ID", x.ID); 
    addedRow.SetField("ParamX", x.ParamX); 
    addedRow.SetField("ParamA", x.ParamA); 
    addedRow.SetField("ParamB", x.ParamB); 
    addedRow.SetField("ParamC", x.ParamC); 
} 

對於它的價值,這裏有一個擴展方法,允許通過反射從IEnumerable<anything>創建:

public static class Extensions 
{ 
    public static DataTable ToDataTable<T>(this IEnumerable<T> data) 
    { 
     PropertyDescriptorCollection props = 
      TypeDescriptor.GetProperties(typeof(T)); 
     DataTable table = new DataTable(); 
     for (int i = 0; i < props.Count; i++) 
     { 
      PropertyDescriptor prop = props[i]; 
      table.Columns.Add(prop.Name, prop.PropertyType); 
     } 
     object[] values = new object[props.Count]; 
     foreach (T item in data) 
     { 
      for (int i = 0; i < values.Length; i++) 
      { 
       values[i] = props[i].GetValue(item); 
      } 
      table.Rows.Add(values); 
     } 
     return table; 
    } 
} 

然後您不需要手動創建或填充表格:

DataTable Table4 = query.ToDataTable(); 
+0

非常感謝您的完整和明確的答案! – madace

+0

thanx很多!現在我明白它應該如何完成! – madace