using System.Collections; using System.Collections.Generic; using System.Linq; using System; namespace CommonLibrary { /// /// Helper methods for operating on collections/IEnumerables /// public static class CollectionTools { /// /// Join each item in the collection together with the glue string, returning a single string /// Each object in the collection will be converted to string with ToString() /// /// /// /// public static string Join(this ICollection collection, string glue) { string returnVal = null; if (collection != null) { foreach (object o in collection) { if (returnVal == null) { returnVal = o.ToString(); } else { returnVal = returnVal + glue + o; } } } return returnVal; } /// /// Checks whether a collection is the same as another collection /// /// The current instance object /// The collection to compare with /// The comparer object to use to compare each item in the collection. If null uses EqualityComparer(T).Default /// True if the two collections contain all the same items in the same order public static bool IsEqualTo(this IEnumerable value, IEnumerable compareList, IEqualityComparer comparer) { if (value == compareList) { return true; } else if (value == null || compareList == null) { return false; } else { if (comparer == null) { comparer = EqualityComparer.Default; } IEnumerator enumerator1 = value.GetEnumerator(); IEnumerator enumerator2 = compareList.GetEnumerator(); bool enum1HasValue = enumerator1.MoveNext(); bool enum2HasValue = enumerator2.MoveNext(); try { while (enum1HasValue && enum2HasValue) { if (!comparer.Equals(enumerator1.Current, enumerator2.Current)) { return false; } enum1HasValue = enumerator1.MoveNext(); enum2HasValue = enumerator2.MoveNext(); } return !(enum1HasValue || enum2HasValue); } finally { if (enumerator1 != null) enumerator1.Dispose(); if (enumerator2 != null) enumerator2.Dispose(); } } } /// /// Checks whether a collection is the same as another collection /// /// The current instance object /// The collection to compare with /// True if the two collections contain all the same items in the same order public static bool IsEqualTo(this IEnumerable value, IEnumerable compareList) { return IsEqualTo(value, compareList, null); } /// /// Checks whether a collection is the same as another collection /// /// The current instance object /// The collection to compare with /// True if the two collections contain all the same items in the same order public static bool IsEqualTo(this IEnumerable value, IEnumerable compareList) { return IsEqualTo(value.OfType(), compareList.OfType()); } } }