using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Sarand.Net.Standard.Base.Utils { //======================================================================= public static class ListUtil { //------------------------------------------------------------------- public static void ClearAndDispose(this IList values) where T : IDisposable { while (values.Count > 0) { T value = values[0]; values.RemoveAt(0); value.Dispose(); } } //------------------------------------------------------------------- /// Is the list empty public static Boolean IsEmpty(this IEnumerable items) { return items.Count() == 0; } //------------------------------------------------------------------- /// /// Is the value in the list of items. /// NB String values are compared case-sensitive. /// Use InCI() for case-insensitive string comparison. /// public static Boolean In(this T item, IEnumerable items) { return items.Contains(item); } /// Is the String in the list of items [case-insensitive] public static Boolean InCI(this String item, IEnumerable items) { return items.ContainsCI(item); } //------------------------------------------------------------------- public enum Equality { /// Exact - exact match between items in each list. Exact = 0x01, /// Unique values only - ignores number of instances of each value. UniqueValuesOnly = 0x02, } /// /// Compare content of two lists. /// - Exact ensures precise number and sequence of elements. /// - Unique allows any number and sequence as long as each item is present in both lists. /// public static bool Equals(this IList sourceList, IList targetList, Equality equality) { bool sameLength = (sourceList.Count == targetList.Count); if (equality == Equality.Exact) { // List must contain exactly the same members in each position. if (!sameLength) return false; for (int idx = 0; idx < sourceList.Count; idx++) { if (!sourceList[idx].Equals(targetList[idx])) return false; } return true; } // Compare just the unique values. if (sourceList.Except(targetList).Any()) return false; if (targetList.Except(sourceList).Any()) return false; return true; } //------------------------------------------------------------------- /// /// Remove the specified range of items from the list to a new list. /// public static List ExtractRange(this List values, int index, int count) { List extractedValues = new List(); if (values.Any()) { count = Math.Min(values.Count(), count); extractedValues.AddRange(values.GetRange(index, count)); values.RemoveRange(index, count); } return extractedValues; } //------------------------------------------------------------------- } //======================================================================= }