Datatable column into a string with string.join

14,355

Your code seams correct.

If you have a datatable with one column like this:

Test
====
123
456

And apply your code, you will get the string "123, 456"

// Init datatable
var dt = new DataTable();            
dt.Columns.Add("Test");
dt.Rows.Add(dt.NewRow()["Test"] = "123");
dt.Rows.Add(dt.NewRow()["Test"] = "456");

// Join columns
string s = string.Join(", ", dt.Rows.OfType<DataRow>().Select(r => r[0].ToString()));
Share:
14,355
devC
Author by

devC

Updated on June 14, 2022

Comments

  • devC
    devC almost 2 years

    I have a datatable that contains a single column. I want to join all the rows in this datatable in to a single string with string.join

    I used the following but it gives me the error best overloaded method for string.join(string, string[]) has some invalid arguments.

     string s = string.Join(", ", ds.Tables[1].Rows.OfType<DataRow>().Select(r => r[0].ToString()));
    

    Can someone help me with writing it correct?

    I was referring to the following to get that code: Store each DataTable Column in string var