Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将行中的所有列值连接起来,然后将数据表中的所有行连接成单个字符串?_C#_.net_Linq_Datatable - Fatal编程技术网

C# 如何将行中的所有列值连接起来,然后将数据表中的所有行连接成单个字符串?

C# 如何将行中的所有列值连接起来,然后将数据表中的所有行连接成单个字符串?,c#,.net,linq,datatable,C#,.net,Linq,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

我试图连接数据表的所有列,然后连接所有行

我尝试了以下代码:

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);
var student=new DataTable();
student.Columns.Add(“Name”,typeof(string));
添加(“国家”,类型(字符串));
对于(inti=0;i string.Format(({0},{1}),”,x.ItemArray[0],x.ItemArray[1])。聚合((x,y)=>x+y);
Console.WriteLine(参数值);
这给了我类似于
(Student0,印度),(Student1,印度),(Student2,印度),(Student3,印度)的输出


这段代码针对两列是固定的,如何使其适用于任意数量的列?

它可以是这样的

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());
注意

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

谢谢Steve,但我想要这样的格式:(itemarray1,itemarray2),(itemarray1,itemarray2)查看代码中的注释,该注释显示了在行值之间使用逗号的方法。我想我们应该将字符串[]作为字符串的第二个参数返回给string.Join()。它应该类似于rows.Select().ToArray()@Amitchauhan See Join(字符串,IEnumerable)