Advertisement
Guest User

Untitled

a guest
Feb 20th, 2019
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. public static IEnumerable<IEnumerable<TValue>> Chunk<TValue>(this IEnumerable<TValue> values, Int32 chunkSize)
  2. {
  3. // TODO: code that chunks
  4. }
  5.  
  6. public static IEnumerable<IEnumerable<TValue>> Chunk<TValue>(this IEnumerable<TValue> values, Int32 chunkSize)
  7. {
  8. var count = values.Count();
  9. var numberOfFullChunks = count / chunkSize;
  10. var lastChunkSize = count % chunkSize;
  11. for (var chunkIndex = 0; chunkSize < numberOfFullChunks; chunkSize++)
  12. {
  13. yield return values.Skip(chunkSize * chunkIndex).Take(chunkSize);
  14. }
  15. if (lastChunkSize > 0)
  16. {
  17. yield return values.Skip(chunkSize * count).Take(lastChunkSize);
  18. }
  19. }
  20.  
  21. static class Ex
  22. {
  23. public static IEnumerable<IEnumerable<TValue>> Chunk<TValue>(
  24. this IEnumerable<TValue> values,
  25. Int32 chunkSize)
  26. {
  27. return values
  28. .Select((v, i) => new {v, groupIndex = i / chunkSize})
  29. .GroupBy(x => x.groupIndex)
  30. .Select(g => g.Select(x => x.v));
  31. }
  32. }
  33.  
  34. static class Ex
  35. {
  36. public static IEnumerable<IEnumerable<TValue>> Chunk<TValue>(
  37. this IEnumerable<TValue> values,
  38. Int32 chunkSize)
  39. {
  40. using(var enumerator = values.GetEnumerator())
  41. {
  42. while(enumerator.MoveNext())
  43. {
  44. yield return GetChunk(enumerator, chunkSize).ToList();
  45. }
  46. }
  47. }
  48. private static IEnumerable<T> GetChunk<T>(
  49. IEnumerator<T> enumerator,
  50. int chunkSize)
  51. {
  52. do{
  53. yield return enumerator.Current;
  54. }while(--chunkSize > 0 && enumerator.MoveNext());
  55. }
  56. }
  57.  
  58. public static IEnumerable<IEnumerable<TValue>> Chunk<TValue>(this IEnumerable<TValue> values, Int32 chunkSize)
  59. {
  60. var valuesList = values.ToList();
  61. var count = valuesList.Count();
  62. for (var i = 0; i < (count / chunkSize) + (count % chunkSize == 0 ? 0 : 1); i++)
  63. {
  64. yield return valuesList.Skip(i * chunkSize).Take(chunkSize);
  65. }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement