且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

创建一个列表,从每个嵌套列表中获取一个元素

更新时间:2023-01-22 07:46:46

您可以阅读有关

You can read about this post of Eric Lippert about computing a Cartesian product with LINQ.

这个想法是访问每个列表,并使用当前的笛卡尔乘积集对该列表进行笛卡尔乘积运算.

The idea is visit each list making a cartesian product of that list with the current cartesian product set.

这是代码:

static IEnumerable<IEnumerable<T>> CartesianProduct<T>(IEnumerable<IEnumerable<T>> sequences)
{
    IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };

    return sequences.Aggregate(emptyProduct, (accumulator, sequence) =>
        from accseq in accumulator
        from item in sequence
        select accseq.Concat(new[] { item }));
}

用法:

var newList = CartesianProduct(oldList);