using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Shared.Extensions { public static class EnumerableExtensions { /// /// Determines whether the collection is null or contains no elements. /// /// The IEnumerable type. /// The enumerable, which may be null or empty. /// /// true if the IEnumerable is null or empty; otherwise, false. /// /// https://stackoverflow.com/a/8582374/2030635 public static bool IsNullOrEmpty(this IEnumerable enumerable) { if (enumerable == null) { return true; } /* If this is a list, use the Count property for efficiency. * The Count property is O(1) while IEnumerable.Count() is O(N). */ if (enumerable is ICollection collection) { return collection.Count < 1; } return !enumerable.Any(); } /// /// Calculate the product of a collection of decimals. /// /// /// public static decimal Product(this IEnumerable enumerable) { //Product of empty collection is 1: https://en.wikipedia.org/wiki/Empty_product if (!enumerable.Any()) return 1M; return enumerable.Aggregate((d1, d2) => d1 * d2); } /// /// Calculate the product of a collection with a selector to translate its items to decimals. /// /// /// /// /// public static decimal Product(this IEnumerable enumerable, Func selector) { //Product of empty collection is 1: https://en.wikipedia.org/wiki/Empty_product if (!enumerable.Any()) return 1M; return enumerable.Aggregate(1M, (s, i2) => s * selector(i2)); } } }