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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With