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

前端 未结 5 2047
傲寒
傲寒 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 19:54

    This extension method, ToArrayOrNull, does not change the type of the contents. seq is an IEnumerable of T. result is an array of T (which you sometimes return as null, but that's still an array of T.

    If you really want to convert an IEnumerable to an IEnumerable (or an array of T?), you should put some constraints on the type parameter (it should be struct, meaning a value type, one that cannot be null), and convert each item instead of the whole result, something like:

        public static T?[] ToArrayOfNullable(this IEnumerable seq)
            where T : struct
        {
            return seq.Select(val => (T?)val).ToArray();
        }
    

    Although I would return an IEnumerable here and convert to an array later, to keep this method simple.

提交回复
热议问题