Get an array of identifiers (values) from datatable

I have a datable with 50 rows and has an identification column. I am trying to get an array that contains only ID, for example:

string [] IDs = (from row in DataTable.Rows
                select row["ID"].toString()).ToArray();

Is there any way to do this. I always get the error message "Could not find query execution ..."

+3
source share
2 answers

Use the method DataTableExtensions.AsEnumerableby adding a link to System.Data.DataSetExtensionsand using System.Data;. Then you can use the following query:

var query = from row in datatable.AsEnumerable()
            select row["ID"].ToString();
string[] ids = query.ToArray();

If you really need an array, you can use the last line above or enclose the query in parentheses and call ToArray()in the same way as you did initially. I'm not a fan of the latter approach at all.

In free syntax, it will be:

string[] ids = datatable.AsEnumerable()
                        .Select(row => row["ID"].ToString())
                        .ToArray();
+4

, . , .

0

All Articles