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.
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#.
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.
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.
ToArray() operator in LINQ is used to convert the input elements in the collection to an Array.
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();
Use type-safe call:
r.Field<string>("Id")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With