如何将DataTable列转换为List

时间:2011-07-07 22:19:27

标签: c# .net list datatable

我有一个包含多列的DataTable。我想从DataTable的第一列中获取List<String>。我怎么能这样做?

7 个答案:

答案 0 :(得分:74)

试试这个:

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

答案 1 :(得分:43)

var list = dataTable.Rows.OfType<DataRow>()
    .Select(dr => dr.Field<string>(columnName)).ToList();

[修改:如果不能编译,请在项目中添加对System.Data.DataSetExtensions的引用]

答案 2 :(得分:6)

你走了。

           DataTable defaultDataTable = defaultDataSet.Tables[0];
           var list = (from x in defaultDataTable.AsEnumerable()
                    where x.Field<string>("column1") == something
                    select x.Field<string>("column2")).ToList();

如果您需要第一栏

           var list = (from x in defaultDataTable.AsEnumerable()
                    where x.Field<string>(1) == something
                    select x.Field<string>(1)).ToList();

答案 3 :(得分:6)

这是你需要的吗?

DataTable myDataTable = new DataTable();
List<int> myList = new List<int>();
foreach (DataRow row in myDataTable.Rows)
{
    myList.Add((int)row[0]);
}

答案 4 :(得分:3)

我为你做了一个样本,我希望这有用......

    static void Main(string[] args)
    {
        var cols = new string[] { "col1", "col2", "col3", "col4", "col5" };

        DataTable table = new DataTable();
        foreach (var col in cols)
            table.Columns.Add(col);

        table.Rows.Add(new object[] { "1", "2", "3", "4", "5" });
        table.Rows.Add(new object[] { "1", "2", "3", "4", "5" });
        table.Rows.Add(new object[] { "1", "2", "3", "4", "5" });
        table.Rows.Add(new object[] { "1", "2", "3", "4", "5" });
        table.Rows.Add(new object[] { "1", "2", "3", "4", "5" });

        foreach (var col in cols)
        {
            var results = from p in table.AsEnumerable()
                          select p[col];

            Console.WriteLine("*************************");
            foreach (var result in results)
            {
                Console.WriteLine(result);
            }
        }


        Console.ReadLine();
    }

答案 5 :(得分:2)

我就像下面一样,在将列设置为AsEnumarable之后,可以进行排序,排序或所需的方式。

 _dataTable.AsEnumerable().Select(p => p.Field<string>("ColumnName")).ToList();

答案 6 :(得分:0)

1。非常简单的代码来迭代数据表并获取列表中的列。

2.code == >>>

 foreach (DataColumn dataColumn in dataTable.Columns)
 {
    var list = dataTable.Rows.OfType<DataRow>()
     .Select(dataRow => dataRow.Field<string> 
       (dataColumn.ToString())).ToList();
 }