Create all combinations of n*m values

后端 未结 2 1869
有刺的猬
有刺的猬 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<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}));                
    }
    
    0 讨论(0)
  • 2020-12-05 16:10
    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)));
        }
    
    0 讨论(0)
提交回复
热议问题