How to convert Linq array [] to int []?

I have a Linq query against a DataRow [] that returns elements from each row. It looks a bit like this:

var query = from row in rows select row["Id"]; 

I want to convert this to int [], but the following code generates an error:

 int[] myIntArray = query.ToArray(); 

Error:

 Cannot implicitly convert type object[] to int[] 

Is there any smart trick to do this job?

+4
source share
1 answer

The DataRow indexer ( row[...] ) returns an object , not an int .
So your implicitly typed request is a collection of object s.

You need to explicitly select int s, for example:

 int[] numbers = rows.Select(r => r.Field<int>("Id")).ToArray(); 

(or just select (int)row["Id"] )

+8
source

Source: https://habr.com/ru/post/1387070/


All Articles