我正在使用linq查询输出一个int数组。但我需要将其传递到只接受int?[]的方法中。
因此,在搜索将int[]转换为int?[]的方法时,我发现了一个似乎可行的解决方案here
以下代码是一个简化的示例,展示了什么起作用和不起作用。
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;
}
}
}
我已经尝试使用这个扩展方法来获取int?[]类型,但是目前还没有成功。
我该如何让我的IEnumerable扩展方法ToArrayOrNull
返回可空类型?
where T : struct
就能完成这个任务。 - DavidG