Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Using LINQ to iterate combinations [closed]
- 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.
- 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}) :
- );
- }
Add Comment
Please, Sign In to add comment