Willy
Willy

Reputation: 10650

LINQ: Convert object[] into int?[]

I have a method, which one of its arguments is an array of objects, for example object[] data. So I would like using LINQ to convert it into an array of int?, how to achieve this. I need to skip only the first element in the array of objects.

For example, something like this (it is not compiling):

int?[] newData = data.Skip(1).Take(data.Length-1).ToArray<int?>();

Thanks!

Upvotes: 1

Views: 1321

Answers (2)

Kirill Bestemyanov
Kirill Bestemyanov

Reputation: 11964

You can use one of two methods:

Cast<int?>
OfType<int?>

Cast will fail if one of elements will not be int?. OfType returns IEnumerable that will contains only elements of type int? from previous array.

So if your array contains elements of type int? excluding first element, you can use

int? [] newData = data.OfType<int?>().ToArray();

Upvotes: 3

I4V
I4V

Reputation: 35363

I don't think you need Take(data.Length - 1)

int?[] newData = data.Skip(1).Take(data.Length - 1).Cast<int?>().ToArray();

It seems

int?[] newData = data.Skip(1).Cast<int?>().ToArray();

is enough (all elements expect the first one).

Upvotes: 10

Related Questions