考虑我有一个以oracle数据库检索的DataTable dt,格式如下
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);
我需要在DataTable dt上使用linq将其更改为以下格式。需要使用逗号分隔产品列,方法是保持其他列相同。
Eno | EHobbies | Esal
-------------------------------------
1 | Cricket | 500
1 | Tennis | 500
1 | Carroms | 500
2 | Cricket | 1000
2 | Volleyball | 1000
答案 0 :(得分:3)
以下方法可行:
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);
答案 1 :(得分:1)
这也有助于:
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"])));