简体   繁体   中英

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

I am trying to concatenate all the columns and then all the rows of a DataTable.

I have tried below code:

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);

This is giving me output like (Student0,India),(Student1,India),(Student2,India),(Student3,India)

This code is fixed for two columns, how can I make it general for any number of columns?

It can be something like this

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

Perhaps you could consider a more traditional approach instead. Sometimes I find Linq less readable and not every scenario are a good fit to use it.
In your case (if even possible) I think that a normal loop conveys better your intentions.

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

NOTE
The code above assumes a lot about your table contents. For example, null values could wreak havoc here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM