创建n*m值的所有组合

And*_*ell 13 c# linq

假设我有这样的数据结构IEnumerable<IEnumerable<object>>:

{
    { A, B }
    { 1, 2, 3 }
    { Z }
}
Run Code Online (Sandbox Code Playgroud)

外部数组可以包含任意数量的内部数组.并且内部数组可以各自独立地包含任意数量的元素.并且为了简单起见,假设没有数组是空的.

我想把它变成IEnumerable<IEnumerable<object>>这样的:

{ { A, 1, Z }, { A, 2, Z }, { A, 3, Z }, { B, 1, Z }, { B, 2, Z }, { B, 3, Z } }
Run Code Online (Sandbox Code Playgroud)

其中包含原始结构中值的每个组合.因此,每个内部数组中的每个元素都通过索引映射到原始外部数组中的元素/数组.

在C#中最简单的方法是什么?

Ale*_*lex 21

您可以使用CartesianProductEric Lippert的方法(取自此处):

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)