我希望通过转换方法将一种类型的列表转换为另一种类型,但只有选择性地转换(如果转换结果为空或不为空)。它显示在下面的代码中。
private List<B> GetBList(List<A> aList)
{
List<B> bList = new List<B>();
foreach (A a in aList)
{
B b = GetB(a);
if (b != null)
{
bList.Add(b);
}
}
return bList;
}
private B GetB(A a)
{
if (a != null)
{
return new B();
}
return null;
}有没有一种方法可以用LINQ写成下面这样的东西。下面函数的问题是,即使转换结果为空,它也始终会移动数据。结果必须是数组(B的数组),输入必须是列表(A的列表)。
private B[] GetBList(List<A> aList)
{
return aList.Select(GetB)?.ToArray() ?? Array.Empty<A>();
}请提个建议。提前感谢!
发布于 2020-06-01 12:34:58
您可以选择with Select(x => GetB(x)),这将返回转换后的对象。那么你应该用Where(x => x != null)对其进行过滤。然后将其转换为array。
请注意,我在aList之后使用?作为aList?.Select,因此当aList对象为null时,它将处理这种情况。
private B[] GetBList(List<A> aList)
{
return aList?.Select(x => GetB(x)).Where(x => x != null).ToArray() ?? Array.Empty<B>();
}编辑如果也使用Select(GetB),则可以使用Select(x => GetB(x))。
private B[] GetBList(List<A> aList)
{
return aList?.Select(GetB).Where(x => x != null).ToArray() ?? Array.Empty<B>();
}https://stackoverflow.com/questions/62125627
复制相似问题