gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 11:58:52 25 4
gpt4 key购买 nike

我正在尝试解析 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

我的输出 DataTable 应该是这样的:

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 中需要帮助。

最佳答案

您可以像这样将您的地点分成多行:

// 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

关于c# - 基于具有逗号分隔值的列创建多个 DataTable 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58088471/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com