Reputation: 128
I have the same issue as here is LINQ join two DataTables but my datatables are made on runtime like
DataTable dtTML = (DataTable)JsonConvert.DeserializeObject(Convert.ToString(data.Json.Args[0]["TML"]), (typeof(DataTable)));
the solution that someone gave is fine but I am getting error on datarows2 at
select dtResult.LoadDataRow(new object[]
{
dataRows2.Field<int>("stock") // here is error : does not exist in current context
}
while dataRows1.Field(s) are fine
Upvotes: 0
Views: 187
Reputation: 30022
I can't see what's wrong with this approach :
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();
You can do whatever you want using it. If you need the result to be a Datatable , just use this method [ ListToDataTable ] to convert List to 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;
Upvotes: 1