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);
This also helps:
DataTable newDt = new DataTable();
newDt.Columns.Add("Eno", typeof(int));
newDt.Columns.Add("EHobbies", typeof(string));
newDt.Columns.Add("Esal", typeof(int));
dt.AsEnumerable().ToList()
.ForEach(row => row["EHobbies"].ToString().Split(',').ToList()
.ForEach(item => newDt.Rows.Add(row["Eno"], item, row["Esal"])));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.