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

前端 未结 5 2032
傲寒
傲寒 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:04

    I know that it's not correct answer for your question but there is a bit different solution - if you want to keep order and collection length.

    public static class EnumerableExtensions
    {
        public delegate bool ParseDelegate(string input, out T value) where T : struct;
    
        public static T?[] ToNullable(this string[] values, ParseDelegate parseMethod) where T : struct
        {
            IEnumerable cos = values.Select(s =>
            {
                T result;
                if (parseMethod(s, out result))
                {
                    return (T?)result;
                }
    
                return null;
            });
    
            return cos.ToArray();
        }
    }
    

    usage:

    var cos = new[] { "1", "", "3", "True" };
    int?[] eee= cos.ToNullable(int.TryParse); // 1, null, 3, null
    float?[] ada = cos.ToNullable(float.TryParse); // 1, null, 3, null
    bool?[] asd3 = cos.ToNullable(bool.TryParse); // null, null, null, true
    

提交回复
热议问题