【问题标题】:How can I concatenate all the column values in a row, and then concatenate all rows in a DataTable into a single string?如何连接一行中的所有列值,然后将 DataTable 中的所有行连接成一个字符串?
【发布时间】:2015-08-29 15:39:40
【问题描述】:

我正在尝试连接所有列,然后连接 DataTable 的所有行。

我试过下面的代码:

var student = new DataTable();
student.Columns.Add("Name", typeof(string));
student.Columns.Add("Country", typeof(string));

for (int i = 0; i <= 3; i++)
{
    DataRow dr = student.NewRow();
    dr["Name"] = "Student" + i;
    dr["Country"] = "India";
    student.Rows.Add(dr);
}

List<DataRow> rows = (from DataRow row in student.Rows select row).ToList();

var paramValues = rows.Select(x => string.Format("({0},{1}),", x.ItemArray[0], x.ItemArray[1])).Aggregate((x, y) => x + y).TrimEnd(',');

Console.WriteLine(paramValues);

这给了我像(Student0,India),(Student1,India),(Student2,India),(Student3,India)这样的输出

此代码固定用于两列,我怎样才能使其适用于任意数量的列?

【问题讨论】:

    标签: c# .net linq datatable


    【解决方案1】:

    可能是这样的

    var paramValues = String.Join(",", 
                         rows.Select(x => "(" + String.Join(",", x.ItemArray) + ")" ));
    

    【讨论】:

    • 我认为我们应该将 string[] 作为第二个参数返回给 string.Join() 。它应该类似于 rows.Select().ToArray(); ??
    • @Amitchauhan 请参阅 Join(String, IEnumerable) docs.microsoft.com/en-us/dotnet/api/…
    【解决方案2】:

    也许您可以考虑采用更传统的方法。有时我发现 Linq 的可读性较差,而且并非所有场景都适合使用它。
    在您的情况下(如果可能的话),我认为正常循环可以更好地传达您的意图。

    StringBuilder sb = new StringBuilder();
    foreach (DataRow row in student.Rows)
    {
        // Concatenate all 
        sb.Append("(" + string.Join(",", row.ItemArray) + ")");
        sb.AppendLine();  // Add a new line (or a sb.Append(",") for a comma)
    }
    Console.WriteLine(sb.ToString());
    

    注意
    上面的代码对您的表格内容做了很多假设。例如,空值可能会在这里造成严重破坏。

    【讨论】:

    • 谢谢史蒂夫,但我想要这样的格式:(itemarray1, itemarray2),(itemarray1, itemarray2)
    • 查看代码中的注释,该注释显示了在行值之间使用逗号的方式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 2014-12-17
    • 2023-02-02
    • 1970-01-01
    相关资源
    最近更新 更多