3

考虑我有一个从 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
4

2 回答 2

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);
于 2013-05-03T13:48:06.237 回答
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"])));
于 2013-05-03T13:56:13.247 回答