如何将 int[] 类型转换为 int?[]

ooX*_*1sh 3 c# linq ienumerable extension-methods nullable

我正在使用 linq 查询来输出 int 数组。但我需要将其传递给仅接受 int?[] 的方法。

因此,在搜索了将 int[] 转换为 int?[] 的方法之后,我发现了一些似乎可以在这里工作的东西

以下代码是一个简化的示例,显示了哪些内容有效,哪些无效。

using System;
using System.Collections.Generic;
using System.Web;
using System.Linq;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // working...
            int[] vids1 = new[] { "", "1", "2", "3" }
                .Where(x => !String.IsNullOrWhiteSpace(x))
                .Select(x => Convert.ToInt32(x))
                .ToArray();

            foreach(int i in vids1) 
            {
                System.Diagnostics.Debug.WriteLine(i.ToString());
            }

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

    public static class IEnumerableExtensions
    {
        public static T?[] ToArrayOrNull<T>(this IEnumerable<T> seq)
        {
            var result = seq.ToArray();

            if (result.Length == 0)
                return null;

            return result;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经尝试过这个扩展方法,试图让它传回 int?[] 类型,但到目前为止还没有运气。

如何让 IEnumerable 扩展ToArrayOrNull传回可空类型?

Jak*_*rtz 5

int?[]是一个数组int?。您所需要的只是更改 lambda in Select,以返回一个int?

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

如果您已经有一个int[],您可以使用Cast()将元素转换为int?

int[] ints = { 1, 2, 3 };
int?[] nullableInts = ints.Cast<int?>().ToArray();
Run Code Online (Sandbox Code Playgroud)