Michael
Michael

Reputation: 13616

How to make int array Nullable?

I have this code:

var contractsID = contracts.Select(x => x.Id);
int?[] contractsIDList = contractsID.ToArray();//for debug

In this line:

int?[] contractsIDList = contractsID.ToArray();//for debug

I get this error:

Can not implicitly convert type int[] to int

what i try to do is to make contractsIDList Nullable type.

How to make int array Nullable?

Upvotes: 19

Views: 39186

Answers (4)

Ramankingdom
Ramankingdom

Reputation: 1486

Use this One

int?[] contractsIDList = contractsID.ConvertAll<int?>((i) => { int? ni = i; return ni; }).ToArray();

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460058

Arrays are always reference types - so they're already nullable.

But i guess that you actually want to get an int?[] from an int[](because the Id is not nullable). You can use Array.ConvertAll:

int[] contractsID = contracts.Select(x => x.Id).ToArray();
int?[] contractsIDList = Array.ConvertAll(contractsID, i => (int?)i);

or cast it directly in the LINQ query:

int?[] contractsIDList = contracts.Select(x => (int?) x.Id).ToArray();

Upvotes: 10

stuartd
stuartd

Reputation: 73243

The error you should get is:

Can not implicitly convert type int[] to int?[]

Thus you need to convert the values:

int?[] contractsIDList = contractsId.Cast<int?>().ToArray();//for debug

Upvotes: 22

Jakub Lortz
Jakub Lortz

Reputation: 14896

The easiest way in your case is to get int? from the Select:

var contractsID = contracts.Select(x => (int?)x.Id);
int?[] contractsIDList = contractsID.ToArray();

Upvotes: 5

Related Questions