如何DataTable的一列转换为一个列表转换为、列表、DataTable

2023-09-03 09:09:06 作者:你爱的样子我都有

我有多个列的数据表。我希望得到一个名单,其中,字符串> 出DataTable的第一列。我该怎么办呢?

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?

推荐答案

试试这个:

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