zey
zey

Reputation: 6103

Retrieve by lambda query and bind to DataTable in C#

I've created a dataTable ,

   private static DataTable GenerateDataTable()
    {
        DataTable _tempSalaryCalculatoin = new DataTable();
        _tempSalaryCalculatoin.Columns.Add("ID", typeof(string));
        _tempSalaryCalculatoin.Columns.Add("NRC", typeof(string));
        _tempSalaryCalculatoin.Columns.Add("FullName", typeof(string));
        _tempSalaryCalculatoin.Columns.Add("Rank", typeof(string));
        _tempSalaryCalculatoin.Columns.Add("Deduction", typeof(string));
        _tempSalaryCalculatoin.Columns.Add("MontlySalary", typeof(string));
        _tempSalaryCalculatoin.Columns.Add("NetSalary", typeof(string));

    }

And I have Database-Table (Employee) likes

ID    NRC     FullName    FatherName    SpouseName       Rank
1     xxx     xxxxxxx     xxxxxxxxx     xxxxxxxxxx      xxxxxx
2     xxx     xxxxxxx     xxxxxxxxx     xxxxxxxxxx      xxxxxx
3     xxx     xxxxxxx     xxxxxxxxx     xxxxxxxxxx      xxxxxx
4     xxx     xxxxxxx     xxxxxxxxx     xxxxxxxxxx      xxxxxx

Data are just for example .

I retrieve this data using lambda query ,

 DataTable _dtSC = GenerateDataTable(); // Generated by the above method
 var _empData  = db.DBInsContext.Employees.Where(x => x.Rank == "xxx" ).ToList();

I want to convert this _empData to DataTable _dtSc .
Notice that > DataTable _dtSc has only seven columns .
I want to leave the columns (which are not exist in Employee table) as Null or Empty .Such as (Deduction , MontlySalary and NetSalary).

Upvotes: 0

Views: 704

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460238

The simplest and most efficient is using a loop. Note that LINQ is a query- and not a modify-tool:

foreach(var emp in _empData)
{
    var newRow = _dtSC.Rows.Add();
    newRow.SetField("ID", emp.ID);
    // and so on ...
    // you are free to not initialize a field like Deduction
}

Upvotes: 2

Related Questions