【发布时间】:2016-03-12 15:54:39
【问题描述】:
我正在使用 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 传回可为空的类型?
【问题讨论】:
-
您似乎在混合传递一个可为空的 int 数组与返回一个空数组。你想达到什么目的??
-
@PoweredByOrange
where T : struct完成这项工作。
标签: c# linq extension-methods ienumerable nullable