我正在使用linq查询来输出int数组。但我需要将它传递给只接受int?[]的方法。如何将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
回传可空类型?
你似乎是混合经过可空INT的数组与返回一个空数组。你想达到什么目的?? – Scottie
@PoweredByOrange'其中T:struct'完成这项工作。 – DavidG