How to Use LINQ to Optimize a Join of Two DataTables in C#
Answers (2)
Add Answervar result = from dataRows1 in table1.AsEnumerable()
join dataRows2 in table2.AsEnumerable()
on dataRows1.Field<string>("ID") equals dataRows2.Field<string>("ID") into lj
from r in lj.DefaultIfEmpty()
select dtResult.LoadDataRow(new object[]
{
dataRows1.Field<string>("ID"),
dataRows1.Field<string>("name"),
r == null ? 0 : r.Field<int>("stock")
}, false);
- First, create two DataTables that need to be joined. Make sure that the column names and data types match for the columns that need to be joined
- Define the Join Query: Use the LINQ query syntax to define the join query.
var result = from table1 in dataTable1.AsEnumerable() join table2 in dataTable2.AsEnumerable() on table1.Field<int>("ID") equals table2.Field<int>("ID") select new { ID = table1.Field<int>("ID"), Name = table1.Field<string>("Name"), Age = table2.Field<int>("Age") };
var JoinResult = (from p in dt.AsEnumerable()
join t in dtTax.AsEnumerable()
on p.Field<int>(“Tax Id”) equals t.Field<int>(“Tax Id”)
select new
{
ProductName = p.Field<string>(“Product Name”),
BrandName = p.Field<string>(“Brand Name”),
ProductCategory = t.Field<string>(“Product Category”),
TaxCharge = t.Field<int>(“Charge”)
}).ToList();