Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 360
iamserious Avatar asked Mar 14 '11 11:03

iamserious


People also ask

Can we use LINQ on ArrayList in C#?

LINQ with ArrayList You don't need to specify array size unlike traditional array and the size grows as you will add more element into it. However, it is slower than Array but it is more useful when you work with collection. Here, in this example, we will learn how to process data in ArrayList using LINQ C#.

How do I get the inserted record ID in LINQ?

after inserting the record into database it returns your record with created Id. You don't need to call any other method to get the id, you already got that after successful insertion so check your object which you passed in you "InsertOnSubmit" method. Here Customers is your table name.

What is any () in LINQ?

The Any operator is used to check whether any element in the sequence or collection satisfy the given condition. If one or more element satisfies the given condition, then it will return true. If any element does not satisfy the given condition, then it will return false.

What will convert a collection into an array in LINQ?

ToArray() operator in LINQ is used to convert the input elements in the collection to an Array.


2 Answers

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();
like image 104
Jon Skeet Avatar answered Oct 01 '22 03:10

Jon Skeet


Use type-safe call:

r.Field<string>("Id")
like image 26
abatishchev Avatar answered Oct 01 '22 04:10

abatishchev