[英]How to convert an int array to a nullable int array?
Let's say I have an array containing x
members and I want to create another array with the same Length ( x
) and the same integer values: 假设我有一个包含
x
成员的数组,并且我想创建另一个具有相同Length( x
)和相同整数值的数组:
int[] arr = new int[x];
int?[] nullable_arr = arr;
And I can't do this: 我不能这样做:
int?[] arr = new int[x];
Is there an explicit conversion to a nullable type array or something I am not aware of? 是否有明确转换为可空类型数组或我不知道的东西?
Yes, I could simply convert each value in a loop but I'm asking if there is already an easy short way of doing this. 是的,我可以简单地在一个循环中转换每个值,但是我在问是否已经有一个简单的简便方法。
I suggest using Linq : 我建议使用Linq :
int?[] nullable_arr = arr
.Select(item => new int?(item))
.ToArray();
Another aproach by using Array.ConvertAll
method 使用
Array.ConvertAll
方法的另一个方法
var values = new[] {1, 2, 3, 4};
var nullableValues = Array.ConvertAll(ints, value => new int?(value));
Or with providing generic types explicitly 或明确提供通用类型
var nullableValues = Array.ConvertAll<int, int?>(ints, value => value);
您可以使用来自Linq的Cast
int?[] arrNull = arr.Cast<int?>().ToArray();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.