Create all combinations of n*m values

后端 未结 2 1878
有刺的猬
有刺的猬 2020-12-05 15:47

Say I have a data structure of IEnumerable> like this:

{
    { A, B }
    { 1, 2, 3 }
    { Z }
}
2条回答
  •  春和景丽
    2020-12-05 16:08

    You could use CartesianProduct method by Eric Lippert for this (taken from here):

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

提交回复
热议问题