Stephen Gross
Stephen Gross

Reputation: 5724

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

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?

Upvotes: 4

Views: 1094

Answers (1)

SLaks
SLaks

Reputation: 888117

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"])

Upvotes: 8

Related Questions