我遇到的问题与LINQ join two DataTables相同 但我的数据表是在运行时制作的,如
DataTable dtTML = (DataTable)JsonConvert.DeserializeObject(Convert.ToString(data.Json.Args[0]["TML"]), (typeof(DataTable)));
某人给出的解决方案很好,但我在
的datarows2上收到错误select dtResult.LoadDataRow(new object[]
{
dataRows2.Field<int>("stock") // here is error : does not exist in current context
}
而dataRows1.Field(s)很好
答案 0 :(得分:1)
我看不出这种方法有什么问题:
DataTable dt1 = new DataTable();
dt1.Columns.Add("PK", typeof(int));
dt1.Columns.Add("Data1", typeof(int));
DataTable dt2 = new DataTable();
dt2.Columns.Add("FK", typeof(int));
dt2.Columns.Add("Data2", typeof(int));
dt2.Rows.Add(1, 5000);
dt1.Rows.Add(1, 1000);
var Result = (from r1 in dt1.AsEnumerable()
join r2 in dt2.AsEnumerable()
on r1["PK"] equals r2["FK"]
select new
{
A = r1.Field<int>("Data1"),
B = r2.Field<int>("Data2"),
// choose more columns if any
}).ToList();
你可以用它做任何你想做的事。如果您需要将结果作为数据表,只需使用此方法[ ListToDataTable ]将List转换为DataTable:
public static DataTable ListToDataTable<T>(List<T> items)
{
System.ComponentModel.PropertyDescriptorCollection properties =
System.ComponentModel.TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
foreach (System.ComponentModel.PropertyDescriptor prop in properties)
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
foreach (T item in items)
{
DataRow row = table.NewRow();
foreach (System.ComponentModel.PropertyDescriptor prop in properties)
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
table.Rows.Add(row);
}
return table;