How to convert a single datatable column to csv? I have a datatable that have two columns (Id,name) , how can I convert Id column to csv string?
What is the expected result? A string where each id is separated by comma or a string where the id is separated by new-line characters?
However, you can use String.Join
+ LINQ:
string result = String.Join(
Environment.NewLine, // replace with "," if desired
table.AsEnumerable().Select(row => row.Field<int>("ID")));
If you want to write to a file you can do this:
var dt=new DataTable();
dt.Columns.Add("Id",typeof(int));
dt.Columns.Add("name",typeof(string));
dt.Rows.Add(1,"test");
File.WriteAllLines("C:\\test\\test.csv",
dt.AsEnumerable()
.Select(d =>
string.Format("{0},{1}",d.Field<int>("Id"),d.Field<string>("name")))
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With