How to convert a column of DataTable to a List

shrishjain picture shrishjain · Jul 8, 2011 · Viewed 125.6k times · Source

I have a DataTable with multiple columns. I want to get a List<String> out of first column of DataTable. How can I do that?

Answer

Michael Buen picture Michael Buen · Jul 8, 2011

Try this:

static void Main(string[] args)
{
    var dt = new DataTable
    {
        Columns = { { "Lastname",typeof(string) }, { "Firstname",typeof(string) } }
    };
    dt.Rows.Add("Lennon", "John");
    dt.Rows.Add("McCartney", "Paul");
    dt.Rows.Add("Harrison", "George");
    dt.Rows.Add("Starr", "Ringo");

    List<string> s = dt.AsEnumerable().Select(x => x[0].ToString()).ToList();

    foreach(string e in s)
        Console.WriteLine(e);

    Console.ReadLine();
}