aspclassic-core/AspClassic.Scripting/Utils/CollectionExtensions.cs
Jelle Luteijn 484dbfc9d9 progress
2022-05-15 11:19:49 +02:00

92 lines
2.1 KiB
C#

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace AspClassic.Scripting.Utils;
internal static class CollectionExtensions
{
internal static ReadOnlyCollection<T> ToReadOnly<T>(this IEnumerable<T> enumerable)
{
if (enumerable == null)
{
return EmptyReadOnlyCollection<T>.Instance;
}
if (enumerable is ReadOnlyCollection<T> result)
{
return result;
}
if (enumerable is ICollection<T> collection)
{
int count = collection.Count;
if (count == 0)
{
return EmptyReadOnlyCollection<T>.Instance;
}
T[] array = new T[count];
collection.CopyTo(array, 0);
return new ReadOnlyCollection<T>(array);
}
return new ReadOnlyCollection<T>(new List<T>(enumerable).ToArray());
}
internal static T[] ToArray<T>(this IEnumerable<T> enumerable)
{
if (enumerable is ICollection<T> collection)
{
T[] array = new T[collection.Count];
collection.CopyTo(array, 0);
return array;
}
return new List<T>(enumerable).ToArray();
}
internal static bool Any<T>(this IEnumerable<T> source, Func<T, bool> predicate)
{
foreach (T item in source)
{
if (predicate(item))
{
return true;
}
}
return false;
}
internal static TSource Aggregate<TSource>(this IEnumerable<TSource> source, Func<TSource, TSource, TSource> func)
{
using IEnumerator<TSource> 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<T>(this IList<T> list, T item)
{
T[] array = new T[list.Count + 1];
array[0] = item;
list.CopyTo(array, 1);
return array;
}
internal static bool TrueForAll<T>(this IEnumerable<T> collection, Predicate<T> predicate)
{
ContractUtils.RequiresNotNull(collection, "collection");
ContractUtils.RequiresNotNull(predicate, "predicate");
foreach (T item in collection)
{
if (!predicate(item))
{
return false;
}
}
return true;
}
}