如何使int数组为Nullable?

时间:2015-10-06 13:32:25

标签: c# .net

我有这段代码:

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

在这一行:

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

我收到此错误:

  

无法将int []类型隐式转换为int

我尝试做的是使contractIDList为Nullable类型。

如何使int数组为Nullable?

4 个答案:

答案 0 :(得分:11)

应该获取的错误是:

  

无法将int []类型隐式转换为int?[]

因此您需要转换值:

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

答案 1 :(得分:5)

您的最简单方法是从int?获取Select

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

答案 2 :(得分:5)

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

但我想您实际上想从int?[]获得int[](因为Id不可为空)。您可以使用Array.ConvertAll

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

或直接在LINQ查询中投射:

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

答案 3 :(得分:1)

使用此

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