Alex Rivera | Logout

How do I get list of id's as int using LINQ

Asked 2011-03-14T11:52:47.467
10

I have a DataTable, say pdt, in my code. I just want to select all table["id"] and populate then in an integer array.

I can go ahead with a foreach but I am trying to learn Lambda expressions. I can't figure out how to deal with this.

I have tried

List<int> Ids = pdt.Select(row => row["Id"]; return Convert.ToInt32(r));

and

int[] Ids = pdt.Select(row => row["Id"]);

but nothing seems to work. I am pretty sure this is a basic question, help out a newbie please.

Edit
Report

1 Answer

26

If you want an array, you need to use the ToArray() extension method... but you also want to use the DataTableExtensions.AsEnumerable() extension method to make the data table strongly typed in terms of a DataRow sequence:

int[] ids = pdt.AsEnumerable()
               .Select(r => (int) r["Id"])
               .ToArray();

EDIT: As noted in abatishchev's answer, an alternative to the explicit cast here would be to use the Field<T> extension method (in DataRowExtenions):

int[] ids = pdt.AsEnumerable()
               .Select(r => r.Field<int>("Id"))
               .ToArray();
answered 2011-03-14T11:55:27.853

Your Answer