Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a single datatable column to csv?

Tags:

c#

csv

datatable

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?

like image 712
Mike Avatar asked Apr 16 '15 11:04

Mike


2 Answers

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")));
like image 187
Tim Schmelter Avatar answered Nov 04 '22 06:11

Tim Schmelter


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")))
        );
like image 28
Arion Avatar answered Nov 04 '22 06:11

Arion