fork download
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. public static class TestExtensions
  5. {
  6. public static IEnumerable<List<T>> GroupsOf<T>(this IEnumerable<T> sequence, int count)
  7. {
  8. if (sequence == null)
  9. {
  10. throw new ArgumentNullException("sequence");
  11. }
  12.  
  13. return GroupsOfImpl<T>(sequence, count);
  14. }
  15.  
  16. private static IEnumerable<List<T>> GroupsOfImpl<T>(IEnumerable<T> sequence, int count)
  17. {
  18. List<T> answer = new List<T>(count);
  19. foreach (T element in sequence)
  20. {
  21. answer.Add(element);
  22. if (answer.Count == count)
  23. {
  24. yield return answer;
  25. answer = new List<T>(count);
  26. }
  27. }
  28.  
  29. if (answer.Count != 0)
  30. {
  31. yield return answer;
  32. }
  33. }
  34. }
  35.  
  36. public class Test
  37. {
  38. public static void Main()
  39. {
  40. var input = new List<int>{1, 2, 3, 3, 2, 1, 0, 4};
  41. foreach (List<int> chunk in input.GroupsOf(3))
  42. {
  43. foreach (int element in chunk)
  44. {
  45. Console.WriteLine(element);
  46. }
  47.  
  48. Console.WriteLine("End Group!");
  49. Console.WriteLine();
  50. }
  51. }
  52. }
Success #stdin #stdout 0.04s 23960KB
stdin
Standard input is empty
stdout
1
2
3
End Group!

3
2
1
End Group!

0
4
End Group!