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:

It is not possible to implicitly convert the type int [] to int

what I'm trying to do is make a contractIDList Nullable type.

How to make int array Nullable?

+5
source share
4 answers

The error you should get:

Cannot implicitly convert type int [] to int? []

So you need to convert the values:

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

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

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

Arrays are always reference types, so they are already nullified.

But I assume that you really want to get int?[] From int[] (because Id not null). You can use Array.ConvertAll :

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

or enter it directly in the LINQ query:

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

Use this

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

Source: https://habr.com/ru/post/1233051/


All Articles