如何连接一行中的所有列值,然后将 DataTable 中的所有行连接成一个字符串?

How can I concatenate all the column values in a row, and then concatenate all rows in a DataTable into a single string?

我正在尝试连接 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)

此代码针对两列是固定的,我怎样才能将其通用化为任意数量的列?

可以是这样的

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

也许您可以考虑采用更传统的方法。有时我发现 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());

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