如何从DataTable获取一列值的列表? [英] How to get list of one column values from DataTable?
问题描述
我有DataTable。
I have DataTable.
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("id", Type.GetType("System.Int32")));
dt.Columns.Add(new DataColumn("name", Type.GetType("System.String")));
// more columns here
我需要 id值列表。
我可以对DataTable中的所有行进行无循环,并且无Linq 吗?
Can I do it without loop over all rows in my DataTable and without Linq?
编辑:
与Sergei进行小讨论后,我还是决定使用循环。
After small discussion with Sergei I decided to use loop anyway.
推荐答案
您可以对数据表使用Linq:
You can use Linq to DataTable:
var ids = dt.AsEnumerable().Select(r => r.Field<int>("id")).ToList();
更新:不使用Linq
UPDATE: Without Linq
List<int> ids = new List<int>(dt.Rows.Count);
foreach(DataRow row in dt.Rows)
ids.Add((int)row["id"]);
为了提高效率,最好使用 row [index]
,而不是 row [columnName]
。第一个只是从columns数组逐列获取索引。后一种情况是从内部字典获取列索引,该内部字典将名称映射到索引,然后才按索引获取列。
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.
这篇关于如何从DataTable获取一列值的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!