c# - 如何编写 C# LINQ 代码以根据条件进行选择
问题描述
我希望通过一种转换方法将一种类型的列表转换为另一种类型,但只能有选择地(如果转换结果为空)。它显示在下面的代码中。
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>();
}
请建议。提前致谢!
解决方案
您可以选择Select(x => GetB(x))
返回转换后的对象。然后你应该用 过滤它Where(x => x != null)
。然后将其转换为array
.
请注意,我已经使用?
afteraList
因为aList?.Select
它会处理aList
object 为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>();
}
推荐阅读
- angularjs - Firebase SPA 重写规则不重定向到 index.html
- python - Python中的“print(not())”是什么?
- python - 使用 Seaborn 在两个轴图形之一中反转色调顺序
- ruby-on-rails - 缺少属性时的验证错误(未定义的方法 `valid_car_type?' for nil:NilClass)
- java - 使用 JDK 12 和 Maven 构建的自包含 JavaFX 12?
- php - 由于 macOS Mojave 10.14.6 更新为 Safari 12.1.2,我无法再登录 Symfony 4.3 应用程序
- javascript - 将事件监听器添加到 foreach 循环中的每个项目
- python - 在 python 2.7 中获取唯一的机器 ID
- python-3.x - Sympy:“应在所有绘制的单变量表达式中使用相同的变量。”
- bash - 测试特定文件集的问题