using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SpriteCompiler.Helpers { public static class EnumerableExtensions { public static IEnumerable> Pairs(this IEnumerable source) { return source.Zip(source.Skip(1), (x, y) => Tuple.Create(x, y)); } public static IEnumerable> GroupAdjacent(this IEnumerable source, Func comparer) { return GroupAdjacent(source, x => x, comparer); } public static IEnumerable> GroupAdjacent(this IEnumerable source, Func keySelector) { return GroupAdjacent(source, keySelector, (a, b) => a.Equals(b)); } public static IEnumerable> GroupAdjacent(this IEnumerable source, Func keySelector, Func comparer) { TKey last = default(TKey); bool haveLast = false; List list = new List(); foreach (TSource s in source) { TKey k = keySelector(s); if (haveLast) { if (!comparer(last, k)) { yield return new GroupOfAdjacent(list, last); list = new List(); list.Add(s); last = k; } else { list.Add(s); last = k; } } else { list.Add(s); last = k; haveLast = true; } } if (haveLast) { yield return new GroupOfAdjacent(list, last); } } } public class GroupOfAdjacent : IEnumerable, IGrouping { public TKey Key { get; set; } private List GroupList { get; set; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return ((System.Collections.Generic.IEnumerable)this).GetEnumerator(); } System.Collections.Generic.IEnumerator System.Collections.Generic.IEnumerable.GetEnumerator() { foreach (var s in GroupList) yield return s; } public GroupOfAdjacent(List source, TKey key) { GroupList = source; Key = key; } } }