创建n*m值的所有组合

本文关键字:组合 创建 | 更新日期: 2023-09-27 17:50:28

假设我有一个IEnumerable<IEnumerable<object>>的数据结构:

{
    { A, B }
    { 1, 2, 3 }
    { Z }
}

其中外部数组可以包含任意数量的内部数组。内部数组可以独立地包含任意数量的元素。为简单起见,假设没有数组为空。

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

{ { A, 1, Z }, { A, 2, Z }, { A, 3, Z }, { B, 1, Z }, { B, 2, Z }, { B, 3, Z } }

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

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

创建n*m值的所有组合

您可以使用Eric Lippert的CartesianProduct方法:

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}));                
}
private static IEnumerable<IEnumerable<object>> GetAllCombinations(IEnumerable<IEnumerable<object>> a)
    {
        if (!a.Skip(1).Any())
        {
            return a.First().Select(x => new[] { x });
        }
        var tail = GetAllCombinations(a.Skip(1)).ToArray();
        return a.First().SelectMany(f => tail.Select(x => new[] { f }.Concat(x)));
    }