using System; using System.Collections.Generic; using System.Linq; using System.Text; public class EmptyCheckEnumerable : IEnumerable { public EmptyCheckEnumerable(IEnumerable src){ this.src = src; } readonly IEnumerable src; Enumerator current; public IEnumerator GetEnumerator() { if (current != null && current.cacheOne) return current; else return current = new Enumerator(src.GetEnumerator()); } public bool IsEmpty { get { GetEnumerator(); return current.IsEmpty; } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } class Enumerator : IEnumerator { public Enumerator(IEnumerator src){ this.src = src; } readonly IEnumerator src; internal bool cacheOne; bool? isEmpty = null; public bool IsEmpty { get { if (isEmpty.HasValue) return isEmpty.Value; // We need to "peek" var res = src.MoveNext(); isEmpty = !res; cacheOne = true; if (isEmpty) Dispose(); return isEmpty.Value; } } public T Current { get { return src.Current; } } public void Dispose() { src.Dispose(); } object System.Collections.IEnumerator.Current { get { return src.Current; } } public bool MoveNext() { if (cacheOne) { cacheOne = false; return !isEmpty.Value; } else { var res = src.MoveNext(); if (!isEmpty.HasValue) isEmpty = !res; return res; } } public void Reset() { throw new NotImplementedException(); } } }