16

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?

Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
Michael
  • 13,950
  • 57
  • 145
  • 288

4 Answers4

19

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
stuartd
  • 70,509
  • 14
  • 132
  • 163
9

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();
Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
5

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();
Jakub Lortz
  • 14,616
  • 3
  • 25
  • 39
1

Use this One

int?[] contractsIDList = contractsID.ConvertAll<int?>((i) => { int? ni = i; return ni; }).ToArray();
Ramankingdom
  • 1,478
  • 2
  • 12
  • 17
  • I wondered if your 100% comment was true, it doesn't work at all. If `contractsID` is an array(what is it) you need to pass the array as parameter, it's not an instance method. – Tim Schmelter Oct 06 '15 at 14:01
  • OP has showed his code: `var contractsID = contracts.Select(x => x.Id);`, it's an `IEnumerable`. – Tim Schmelter Oct 07 '15 at 07:15