更新时间: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);