How to get list of one column values from DataTable?

前端 未结 2 1686
暖寄归人
暖寄归人 2021-02-01 13:28

I have DataTable.

DataTable dt = new DataTable();

dt.Columns.Add(new DataColumn(\"id\", Type.GetType(\"System.Int32\")));
dt.Columns.Add(new DataColumn(\"name\"         


        
相关标签:
2条回答
  • 2021-02-01 13:52

    You can use Linq to DataTable:

    var ids = dt.AsEnumerable().Select(r => r.Field<int>("id")).ToList();
    

    UPDATE: Without Linq

    List<int> ids = new List<int>(dt.Rows.Count);
    foreach(DataRow row in dt.Rows)
        ids.Add((int)row["id"]);
    

    Note for efficiency it's better to use row[index] instead of row[columnName]. First one just gets column by index from columns array. Latter gets column index from internal dictionary which maps names to indexes, and only then gets column by index.

    Another thing to note is initializing list's capacity with rows count. If you will not do this, then internal array of list will be re-created and copied many times (depends on rows count).

    And last thing to say - most efficient way with huge table (if possible) is filtering data on server side.

    0 讨论(0)
  • 2021-02-01 14:05
    List<int> ids = dt.AsEnumerable().Select(r => r.Field<int>("id")).ToList();
    

    OR

    int[] ids = dt.AsEnumerable().Select(r => r.Field<int>("id")).ToArray();
    
    0 讨论(0)
提交回复
热议问题