您不能在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();
datatable或Linq? – andy