基于具有逗号分隔值的列创建多个DataTable行

时间:2019-09-24 21:38:43

标签: c# linq datatable

我正在尝试解析DataTable行中的逗号分隔值,并从中创建单独的行。

这是我要开始的表格的示例:

ID Date        Places
1  09/24/2019  Paris,Tokyo,Rome
2  09/23/2019  London,Florence,Barcelona
3  09/22/2019  Vienna,Rome,London

我的输出数据表应如下所示:

ID Date        Places
1  09/24/2019  Paris
1  09/24/2019  Tokyo
1  09/24/2019  Rome 
2  09/23/2019  London
2  09/23/2019  Florence
2  09/23/2019  Barcelona
3  09/22/2019  Vienna
3  09/22/2019  Rome
3  09/22/2019  London

到目前为止,这是我的代码:

for (int i = 0; i < dataTable.Rows.Count; i++)
{
    string[] places = dataTable.Rows[i][2].ToString().Split(',');

    if (places.Length > 1)
    {
        foreach (string s in places)
        {
            //create a new datarow 
            //get the values for row[i] (ID and Date)
            //assign the place 
        }
    }
}

我需要foreach内的帮助。

1 个答案:

答案 0 :(得分:1)

您可以将自己的位置分成多行,如下所示:

// Use ToList() here so that we can modify the table while iterating over the original rows
foreach (DataRow row in dataTable.Rows.Cast<DataRow>().ToList())
{
    int id = row.Field<int>("ID");
    string date = row.Field<string>("Date");
    string places = row.Field<string>("Places");

    foreach (string place in places.Split(','))
    {
        dataTable.Rows.Add(id, date, place);
    }

    row.Delete();  // delete the original row
}

注意:Field<T>()扩展方法是在System.Data.DataSetExtensions中定义的,因此,如果要使用该方法,则需要在项目中引用该程序集。

正在运行的演示:https://dotnetfiddle.net/zYSWlv

相关问题