生成一个n-ary Cartesian产品示例

Ste*_*hel 3 .net c# linq cartesian-product

我发现,埃里克利珀的帖子在这里都有特定的问题,我有.

问题是我无法理解我应该如何使用2个数量的集合.

var collections = new List<List<MyType>>();
foreach(var item in somequery)
{
    collections.Add(
            new List<MyType> { new MyType { Id = 1} .. n }
        );
}
Run Code Online (Sandbox Code Playgroud)

如何在变量集合上应用笛卡尔积linq查询?

扩展方法是这样的:

static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this 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})                       
        );
 }
Run Code Online (Sandbox Code Playgroud)

这是Eric的2个集合的例子:

var arr1 = new[] {"a", "b", "c"};
var arr2 = new[] { 3, 2, 4 };
var result = from cpLine in CartesianProduct(
                     from count in arr2 select Enumerable.Range(1, count)) 
             select cpLine.Zip(arr1, (x1, x2) => x2 + x1);
Run Code Online (Sandbox Code Playgroud)

Amy*_*y B 5

示例代码已经能够执行"n"笛卡尔积(在示例中它为3).你的问题是你有一个List<List<MyType>>什么时候需要IEnumerable<IEnumerable<MyType>>

IEnumerable<IEnumerable<MyType>> result = collections
  .Select(list => list.AsEnumerable())
  .CartesianProduct();
Run Code Online (Sandbox Code Playgroud)