Using LINQ to Iterate Combinations

Possible duplicate:
Creating all possible combinations
Is there a LINQ way for a Cartesian product? How to generate a combination of N elements with a limited margin of 2 without explicit nested loops

I have a list of lists, and I want to iterate over all possible combinations when I select one item from each internal list. It is quite simple if I know at compile time how many lists there are, but how can I do this when I do not know in advance how many lists there will be?

If I have three lists (and if at compile time I know that there will be exactly three lists), and I want all combinations of selecting one element from each of the three lists I can do easily with LINQ query:

var list1 = new[] { 1, 2 };
var list2 = new[] { 3, 4 };
var list3 = new[] { 5, 6 };
var combinations = from item1 in list1
                   from item2 in list2
                   from item3 in list3
                   select new[] { item1, item2, item3 };
// Results:
// {1, 3, 5}
// {1, 3, 6}
// {1, 4, 5}
// {1, 4, 6}
// {2, 3, 5}
// {2, 3, 6}
// {2, 4, 5}
// {2, 4, 6}

, , ?

var lists = new[] {
    new[] { 1, 2 },
    new[] { 3, 4 },
    new[] { 5, 6 } };
var combinations = ???;

// This particular example happens to be the same inputs as above, so it
// has the same expected outputs. But there could be two lists instead,
// or four, so the three hard-coded "from" clauses won't work.

, LINQ - SelectMany foreach, SelectMany-, SelectMany. -. , . , . , SelectMany .

, , ?

(: , , IEnumerable<T> . , , , , IEnumerable<IEnumerable<int>>, int[][], .)

+5
1

SelectMany SelectMany; Aggregate. ( , , , , ):

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}) :                         
        );
}

, , , , , LINQ.

+2

All Articles