Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separating the column values of DataTable using LINQ

Tags:

c#

.net

linq

Consider i have a DataTable dt retrieved from oracle database in the following format

Eno   |      EHobbies                     |  Esal
-------------------------------------------------
1     |      Cricket,Tennis,Carroms       |  500
2     |      Cricket,Volley               |  1000

//Datatable for above table
DataTable dt = new DataTable("EmployeeTable");
dt.Columns.Add("Eno", typeof(int));
dt.Columns.Add("EHobbies", typeof(string));
dt.Columns.Add("Esal", typeof(int));    

dt.Rows.Add(1, "Cricket,Tennis,Carroms",500 );
dt.Rows.Add(2, "Cricket,Volley",1000);

I need to change this into the following format using linq on the DataTable dt .Need to separate the product column with the help of comma by keeping the other columns same.

Eno   |        EHobbies     |   Esal
-------------------------------------
1     |        Cricket      |    500
1     |        Tennis       |    500
1     |        Carroms      |    500
2     |        Cricket      |    1000
2     |        Volleyball   |    1000
like image 553
user2345976 Avatar asked Dec 29 '25 10:12

user2345976


1 Answers

The following would work:

var newRows = dt.AsEnumerable()
                .SelectMany(r => r.Field<string>("EHobbies")
                                  .Split(',')
                                  .Select(x => new { No = r.Field<int>("Eno"),
                                                     Hobbies = x,
                                                     Sal = r.Field<int>("Esal") }
                                         )
                           );

DataTable result = new DataTable("EmployeeTable");
result.Columns.Add("Eno", typeof(int));
result.Columns.Add("EHobbies", typeof(string));
result.Columns.Add("Esal", typeof(int));

foreach(var newRow in newRows)
    result.Rows.Add(newRow.No, newRow.Hobbies, newRow.Sal);
like image 58
Daniel Hilgarth Avatar answered Dec 31 '25 00:12

Daniel Hilgarth