【问题标题】:Create multiple DataTable rows based on a column with comma separated values基于具有逗号分隔值的列创建多个 DataTable 行
【发布时间】:2019-09-24 21:38:43
【问题描述】:

我正在尝试解析 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 的帮助。

【问题讨论】:

  • 您需要第二个 DataTable,其中只有 ID、Date 和 Place 列并添加到其中。

标签: c# linq datatable


【解决方案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&lt;T&gt;() 扩展方法在System.Data.DataSetExtensions 中定义,因此如果您想使用该方法,您需要在项目中引用该程序集。

工作演示:https://dotnetfiddle.net/zYSWlv

【讨论】:

  • 谢谢,由于某些原因 row.Delete() 正在删除所有添加的行,所以我必须创建新的数据表并开始向其中添加行
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-28
  • 2019-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多