Update DataTable using LinQ

Description

If you have a requirement to update the datatable column value from another datatable column value. Then

Here I am Showing a simple example: you can perform this action also on the database tables data.

You can perform this task by using the Left outer join of LinQ.

1. My Master Datatable data

     private DataTable dt()
           //Master table-----------------
      {  DataTable _dtt = new DataTable();
        _dtt.Columns.Add("id");
        _dtt.Columns.Add("Type");
        _dtt.Rows.Add("1", "ex1");
        _dtt.Rows.Add("2", "ex2");
        _dtt.Rows.Add("3", "ex3");
        _dtt.Rows.Add("4", "ex4");
        _dtt.Rows.Add("5", "ex5");
        _dtt.Rows.Add("6", "ex6");
        return _dtt;}

2. My second child datatable data

    private DataTable dttt()
    {//Child table--------------- 
        DataTable _dtt = new DataTable();
        _dtt.Columns.Add("id");
        _dtt.Columns.Add("Type");
        _dtt.Columns.Add("Discription");
        _dtt.Rows.Add("1", "ex1", "sdfdf");
        _dtt.Rows.Add("2", "ex2", "ttyt");
        _dtt.Rows.Add("3", "ex3", "kjlkl");
        return _dtt;}

3. After that I have a requirement to show all the data of the Master Datatable with the corresponding  'description' column value from the Child table.

4. Linq query

         DataTable _dtMaster = dt();
        _dtMaster.Columns.Add("Discription");
        DataTable _dtChild = dttt();
        _dtMaster.AsEnumerable().Join(_dtChild.AsEnumerable(), _dtmater => Convert.ToString(_dtmater["id"]),
        _dtchild => Convert.ToString(_dtchild["id"]), (_dtmater, _dtchild) => new { _dtmater, _dtchild }).ToList().ForEach(o=>o._dtmater.SetField("Discription",o._dtchild["Discription"].ToString()));
Ebook Download
View all
Learn
View all