using System; using System.Collections.Generic; using System.Collections.ObjectModel; namespace AspClassic.Scripting.Utils; internal static class CollectionExtensions { internal static ReadOnlyCollection ToReadOnly(this IEnumerable enumerable) { if (enumerable == null) { return EmptyReadOnlyCollection.Instance; } if (enumerable is ReadOnlyCollection result) { return result; } if (enumerable is ICollection collection) { int count = collection.Count; if (count == 0) { return EmptyReadOnlyCollection.Instance; } T[] array = new T[count]; collection.CopyTo(array, 0); return new ReadOnlyCollection(array); } return new ReadOnlyCollection(new List(enumerable).ToArray()); } internal static T[] ToArray(this IEnumerable enumerable) { if (enumerable is ICollection collection) { T[] array = new T[collection.Count]; collection.CopyTo(array, 0); return array; } return new List(enumerable).ToArray(); } internal static bool Any(this IEnumerable source, Func predicate) { foreach (T item in source) { if (predicate(item)) { return true; } } return false; } internal static TSource Aggregate(this IEnumerable source, Func func) { using IEnumerator enumerator = source.GetEnumerator(); if (!enumerator.MoveNext()) { throw new ArgumentException("Collection is empty", "source"); } TSource val = enumerator.Current; while (enumerator.MoveNext()) { val = func(val, enumerator.Current); } return val; } internal static T[] AddFirst(this IList list, T item) { T[] array = new T[list.Count + 1]; array[0] = item; list.CopyTo(array, 1); return array; } internal static bool TrueForAll(this IEnumerable collection, Predicate predicate) { ContractUtils.RequiresNotNull(collection, "collection"); ContractUtils.RequiresNotNull(predicate, "predicate"); foreach (T item in collection) { if (!predicate(item)) { return false; } } return true; } }