我正在使用 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?[]
是一个数组int?
。你所需要的只是改变 lambdaSelect
,返回一个int?
:
int?[] vids2 = new[] { "", "1", "2", "3" }
.Where(x => !String.IsNullOrWhiteSpace(x))
.Select(x => (int?)Convert.ToInt32(x))
.ToArray();
如果您已经有一个int[]
, 您可以使用Cast()
将元素投射到int?
int[] ints = { 1, 2, 3 };
int?[] nullableInts = ints.Cast<int?>().ToArray();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)