using System.Collections; namespace Recyclarr.Common.Extensions; public static class CollectionExtensions { // From: https://stackoverflow.com/a/34362585/157971 public static IReadOnlyCollection AsReadOnly(this ICollection source) { if (source is null) { throw new ArgumentNullException(nameof(source)); } return source as IReadOnlyCollection ?? new ReadOnlyCollectionAdapter(source); } // From: https://stackoverflow.com/a/34362585/157971 private sealed class ReadOnlyCollectionAdapter : IReadOnlyCollection { private readonly ICollection _source; public ReadOnlyCollectionAdapter(ICollection source) { _source = source; } public int Count => _source.Count; public IEnumerator GetEnumerator() { return _source.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public static void AddRange(this ICollection destination, IEnumerable source) { foreach (var item in source) { destination.Add(item); } } public static IEnumerable NotNull(this IEnumerable source) where T : class { return source.Where(x => x is not null).Select(x => x!); } public static IEnumerable NotNull(this IEnumerable source) where T : struct { return source.Where(x => x is not null).Select(x => x!.Value); } public static bool IsEmpty(this ICollection? collection) { return collection is null or {Count: 0}; } public static bool IsEmpty(this IReadOnlyCollection? collection) { return collection is null or {Count: 0}; } public static bool IsNotEmpty(this ICollection? collection) { return collection is {Count: > 0}; } public static IList? ToListOrNull(this IEnumerable source) { var list = source.ToList(); return list.Any() ? list : null; } }