CSharp examples for System.Collections:IEnumerable
This method splits the into sequence of pieces size of each is not more then max length
using System.Text; using System.Linq; using System.Diagnostics.Contracts; using System.Collections.Generic; using System;//w w w.j a v a 2 s . c om public class Main{ /// <summary> /// This method splits the <paramref name="data"/> into sequence of pieces /// size of each is not more then <paramref name="maxLength"/>. /// (Size of each except the last is equal to <paramref name="maxLength"/>, size of the last can be less). /// </summary> [Pure] public static IEnumerable<T[]> SplitIntoPieces<T>(this T[] data, int maxLength) { Contract.Requires(data != null && maxLength > 0); if(maxLength == -1 || maxLength >= data.Length) { yield return data; yield break; } int bufferOfsetInData = 0; do { int pieceLength = Math.Min(data.Length - bufferOfsetInData, maxLength); var buffer = new T[pieceLength]; Array.Copy(data, bufferOfsetInData, buffer, 0, pieceLength); bufferOfsetInData += pieceLength; yield return buffer; } while(data.Length > bufferOfsetInData); } }