How to convert type int[] to int?[]

前端 未结 5 2058
傲寒
傲寒 2021-01-24 19:16

I\'m using a linq query to output an int array. But I need to pass this into a method that only accepts int?[].

So after searching on ways to convert int[] to int?[] I

5条回答
  •  佛祖请我去吃肉
    2021-01-24 20:03

    int?[] is an array of int?. All you need is change lambda in Select, to return an int?:

    int?[] vids2 = new[] { "", "1", "2", "3" }
        .Where(x => !String.IsNullOrWhiteSpace(x))
        .Select(x => (int?)Convert.ToInt32(x))
        .ToArray();
    

    If you already have an int[], you can use Cast() to cast the elements to int?

    int[] ints = { 1, 2, 3 };
    int?[] nullableInts = ints.Cast().ToArray();
    

提交回复
热议问题