Guest User

Untitled

a guest
Aug 17th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1. Using LINQ to iterate combinations [closed]
  2. var list1 = new[] { 1, 2 };
  3. var list2 = new[] { 3, 4 };
  4. var list3 = new[] { 5, 6 };
  5. var combinations = from item1 in list1
  6. from item2 in list2
  7. from item3 in list3
  8. select new[] { item1, item2, item3 };
  9. // Results:
  10. // {1, 3, 5}
  11. // {1, 3, 6}
  12. // {1, 4, 5}
  13. // {1, 4, 6}
  14. // {2, 3, 5}
  15. // {2, 3, 6}
  16. // {2, 4, 5}
  17. // {2, 4, 6}
  18.  
  19. var lists = new[] {
  20. new[] { 1, 2 },
  21. new[] { 3, 4 },
  22. new[] { 5, 6 } };
  23. var combinations = ???;
  24.  
  25. // This particular example happens to be the same inputs as above, so it
  26. // has the same expected outputs. But there could be two lists instead,
  27. // or four, so the three hard-coded "from" clauses won't work.
  28.  
  29. static IEnumerable<IEnumerable<T>> CartesianProduct<T>(
  30. this IEnumerable<IEnumerable<T>> sequences)
  31. {
  32. IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };
  33. return sequences.Aggregate(
  34. emptyProduct,
  35. (accumulator, sequence) =>
  36. from accseq in accumulator
  37. from item in sequence
  38. select accseq.Concat(new[] {item}) :
  39. );
  40. }
Add Comment
Please, Sign In to add comment