Kamil
Kamil

Reputation: 13941

How to get list of one column values from 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

I need list of "id" values.

Can I do it without loop over all rows in my DataTable and without Linq?

Edit:

After small discussion with Sergei I decided to use loop anyway.

Upvotes: 63

Views: 134044

Answers (3)

chara
chara

Reputation: 121

AsEnumerable() does not work for me so use:

List<string> ids = dt.Rows.Cast<DataRow>().Select(r => Convert.ToString(r["id"])).ToList();

For other data types use the appropriate Convert.XXX variant.

Upvotes: 1

user2343600
user2343600

Reputation: 9

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

OR

int[] ids = dt.AsEnumerable().Select(r => r.Field<int>("id")).ToArray();

Upvotes: 1

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236328

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.

Upvotes: 110

Related Questions