如何展平 IEnumerables 的 IEnumerables 的串联

How to flatten out the concatenation of IEnumerables of IEnumerables

我知道某处有一个 LINQ 解决方案,但我看不到它。我的情况是这样的:我有一个 base class(暂时称它为 B),它接受可变参数并使用它来初始化一个 readonly 字段,它恰好是一个 IReadonlyCollection(我们称这个字段为 List)。

我有两个 derived classes(我们称它们为 D1D2),它们对可变参数参数做完全相同的事情,将其传递给base class 构造函数,没有问题。

但是我有第三个 derived class(我们称这个为 D_1_and_2),派生自相同的 base class,B,它接受作为其参数构造函数 2 个数组,一个 D1[] 类型,另一个 D2[] 类型。

我的问题是,我必须以某种方式将第一个参数(D1[] 参数)List 字段的所有元素相互连接起来,并与第二个参数的 List 字段的所有元素连接起来并传递在构建期间将结果数组添加到 base class。波纹管是代码中问题的说明。

public class CollectionElement
{

}

public class BaseClass
{
    public readonly IReadOnlyCollection<CollectionElement> TheCollection;

    public BaseClass(params CollectionElement[] arg)
    {
        TheCollection = Arrays.AsReadOnly(arg);
    }
}

public class DerivedClassA : BaseClass
{
    public DerivedClass(params CollectionElement[] arg)
        :base(arg){}
}

public class DerivedClassB : BaseClass
{
    public DerivedClass(params CollectionElement[] arg)
        :base(arg){}
}

public class DerivedClassA_Plus_B : BaseClass
{
    public DerivedClass(DerivedClassA[] argA, DerivedClassB[] argB)
        :base(/*[don't know]*/){}
}

我认为您正在寻找 Enumerable.SelectMany to project and then flatten the elements, and then Enumerable.Concat 将两个序列连接在一起。

public class DerivedClassA_Plus_B : BaseClass
{
    public DerivedClass(DerivedClassA[] argA, DerivedClassB[] argB)
        :base(Combine(argA, argB)) { }

    private static CollectionElement[] Combine(DerivedClassA[] argA, DerivedClassB[] argB)
    {
        var a = argA.SelectMany(x => x.TheCollection);
        var b = argB.SelectMany(x => x.TheCollection);
        return a.Concat(b).ToArray();
    }
}