using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; namespace Microsoft.Research.DynamicDataDisplay.Common.Auxiliary { /// /// Contains extension methods for IEnumerable. /// public static class IEnumerableExtensions { /// /// Gets the value indicating wheter count of elements in a given sequence is greater or equal than specified value. /// /// /// The enumerable. /// The count. /// public static bool CountGreaterOrEqual(this IEnumerable enumerable, int count) { int counter = 0; using (var enumerator = enumerable.GetEnumerator()) { while (counter < count && enumerator.MoveNext()) { counter++; } } return counter == count; } /// /// Splits the specified source sequnce into a sequence of sequences, with the length of inner sequence not longer than /// specified maximal count. /// /// /// The source. /// The max count. /// public static IEnumerable> Split(this IEnumerable source, int maxCount) { using (var enumerator = new FixedEnumeratorWrapper(source.GetEnumerator())) { do { var enumerable = new FixedEnumerable(enumerator); yield return enumerable.Take(maxCount); } while (enumerator.CanMoveNext); } } private sealed class FixedEnumeratorWrapper : IEnumerator { private readonly IEnumerator enumerator; public FixedEnumeratorWrapper(IEnumerator enumerator) { this.enumerator = enumerator; } #region IEnumerator Members public T Current { get { return enumerator.Current; } } #endregion #region IDisposable Members public void Dispose() { //enumerator.Dispose(); } #endregion #region IEnumerator Members object IEnumerator.Current { get { return enumerator.Current; } } private bool canMoveNext = false; public bool CanMoveNext { get { return canMoveNext; } } public bool MoveNext() { canMoveNext = enumerator.MoveNext(); return canMoveNext; } public void Reset() { enumerator.Reset(); } #endregion } private sealed class FixedEnumerable : IEnumerable { private readonly IEnumerator enumerator; public FixedEnumerable(IEnumerator enumerator) { this.enumerator = enumerator; } #region IEnumerable Members public IEnumerator GetEnumerator() { return enumerator; } #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { return enumerator; } #endregion } } }