Friday, June 29, 2018

Bind data from Linq to DataTable with out Loop

1. Create DataTable with structure:

 DataTable dt = new DataTable();
            dt.Columns.Add("EmployeeId", typeof(string));
            dt.Columns.Add("Email", typeof(string));
            dt.Columns.Add("EmployeeName", typeof(string));
            dt.Columns.Add("Department", typeof(string));

2. Write Linq query as below:
            var Result = from objEmpDetail in empDetails.AsEnumerable()
                         where (a.DepartmentId ==10001)
                         select dt.LoadDataRow(new object[]
                         {
                            objEmpDetail.EmployeeId,
                            objEmpDetail.Email,
                            objEmpDetail.EmployeeName,
                           objEmpDetail.Department
                         }, false);

3. Copy the result to datatable:
            Result.CopyToDataTable();