Guest User

Untitled

a guest
Apr 25th, 2018
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.84 KB | None | 0 0
  1. public static class ListExtentions
  2. {
  3. public static IEnumerable Cartesian(this IEnumerable<IEnumerable> items)
  4. {
  5. var slots = items
  6. // initialize enumerators
  7. .Select(x => x.GetEnumerator())
  8. // get only those that could start in case there is an empty collection
  9. .Where(x => x.MoveNext())
  10. .ToArray();
  11.  
  12. while (true)
  13. {
  14. // yield current values
  15. yield return slots.Select(x => x.Current);
  16.  
  17. // increase enumerators
  18. foreach (var slot in slots)
  19. {
  20. // reset the slot if it couldn't move next
  21. if (!slot.MoveNext())
  22. {
  23. // stop when the last enumerator resets
  24. if (slot == slots.Last()) { yield break; }
  25. slot.Reset();
  26. slot.MoveNext();
  27. // move to the next enumerator if this reseted
  28. continue;
  29. }
  30. // we could increase the current enumerator without reset so stop here
  31. break;
  32. }
  33. }
  34. }
  35. }
Add Comment
Please, Sign In to add comment