// © 2008 IDesign Inc. All rights reserved //Questions? Comments? go to //http://www.idesign.net using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; public static class CollectionExtensions { public static void ForEach(this IEnumerable collection,Action action) { if(collection == null) { throw new ArgumentNullException("collection"); } if(action == null) { throw new ArgumentNullException("action"); } foreach(T item in collection) { action(item); } } public static IEnumerable ConvertAll(this IEnumerable collection,Converter converter) { if(collection == null) { throw new ArgumentNullException("collection"); } if(converter == null) { throw new ArgumentNullException("converter"); } foreach(T item in collection) { yield return converter(item); } } public static IEnumerable Complement(this IEnumerable collection1,IEnumerable collection2) { foreach(T item in collection1) { if(collection2.Contains(item) == false) { yield return item; } } } public static IEnumerable Except(IEnumerable collection1,IEnumerable collection2) where T : IEquatable { IEnumerable complement1 = Complement(collection1,collection2); IEnumerable complement2 = Complement(collection2,collection1); return complement1.Union(complement2); } public static IEnumerable Sort(this IEnumerable collection) { if(collection == null) { throw new ArgumentNullException("collection"); } List list = new List(collection); list.Sort(); foreach(T item in list) { yield return item; } } public static int FindIndex(this IEnumerable collection,T value) where T : IEquatable { if(collection == null) { throw new ArgumentNullException("collection"); } using(IEnumerator iterator = collection.GetEnumerator()) { int index = 0; while(iterator.MoveNext()) { if(iterator.Current.Equals(value) == false) { index++; } else { return index; } } return -1; } } public static U[] UnsafeToArray(this System.Collections.IEnumerable collection,Converter converter) { if(collection == null) { throw new ArgumentNullException("collection"); } if(converter == null) { throw new ArgumentNullException("converter"); } var col = collection.UnsafeToArray(); return col.ConvertAll(converter) as U[]; } public static T[] UnsafeToArray(this System.Collections.IEnumerable collection) { if(collection == null) { throw new ArgumentNullException("collection"); } return Collection.UnsafeToArray(collection); } }