Update Datatable using Linq in C#

Description: if you have a requirement to update datatable column value from another datatable column value.
Here  I have to Show the simple example: you can perform this action also on database tables data.
you can perform this task by using 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 data of Master Datatable with corresponding  'description' column value from 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()));

         
After this query record look like this:

If there is anything wrong with this please let me know.

  
Author

Priti Kumari

I am technical blogger.I blogs at www.c-Sharpcorner.com and https://aspdotnetmyblog.blogspot.in/.

No comments:

Post a Comment