首页 > 解决方案 > 如何编写 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>();
}

请建议。提前致谢!

标签: c#linq

解决方案


您可以选择Select(x => GetB(x))返回转换后的对象。然后你应该用 过滤它Where(x => x != null)。然后将其转换为array.

请注意,我已经使用?afteraList因为aList?.Select它会处理aListobject 为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>();
}

推荐阅读