Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linq

I've got a Linq query against a DataRow[] that returns elements from each row. Looks a bit like this:

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

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

int[] myIntArray = query.ToArray();

The error is:

Cannot implicitly convert type object[] to int[]

Is there some clever trick for making this work?

like image 668
Stephen Gross Avatar asked Feb 22 '23 02:02

Stephen Gross


1 Answers

The DataRow indexer (row[...]) returns object, not int.
Therefore, your implicitly-typed query is a set of objects.

You need to explicitly select ints, like this:

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

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

like image 118
SLaks Avatar answered Jun 06 '23 08:06

SLaks