Sunday, February 22, 2015

Merge Two Datatable using linq


Merge Two Datatable using linq
 
private void showEmployeeRecords()
{
DataTable dtEmployee = getEmployeeRecords();
DataTable dtDepartment = getDepartmentRecords();

#region Second solution using linq

//==== First Datatable structure should be defined =====================

DataTable dt = new DataTable();
dt.Columns.Add("EmployeeID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("FatherName", typeof(string));
dt.Columns.Add("DepartmentName", typeof(string));

//====== Wrting query for join between two data tables ===========================

var result = from dataRows1 in dtEmployee.AsEnumerable()
join dataRows2 in dtDepartment.AsEnumerable()
on dataRows1.Field("DeptID") equals dataRows2.Field("DeptID")

select dt.LoadDataRow(new object[]
{
dataRows1.Field("EmployeeID"),
dataRows1.Field("EmployeeName"),
dataRows1.Field("FatherName"),
dataRows1.Field("Address"),
dataRows2.Field("DeptName")
}, false);

//==== copy output of result into datatable named 'dt' =============================

result.CopyToDataTable(); // This point records will be loaded in dt data table

#endregion

}

No comments:

Post a Comment