using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Shared.Extensions
{
public static class EnumerableExtensions
{
/// <summary>
/// Determines whether the collection is null or contains no elements.
/// </summary>
/// <typeparam name="T">The IEnumerable type.</typeparam>
/// <param name="enumerable">The enumerable, which may be null or empty.</param>
/// <returns>
/// <c>true</c> if the IEnumerable is null or empty; otherwise, <c>false</c>.
/// </returns>
/// <source>https://stackoverflow.com/a/8582374/2030635</source>
public static bool IsNullOrEmpty<T>(this IEnumerable<T> 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<T> collection)
{
return collection.Count < 1;
}
return !enumerable.Any();
}
/// <summary>
/// Calculate the product of a collection of decimals.
/// </summary>
/// <param name="enumerable"></param>
/// <returns></returns>
public static decimal Product(this IEnumerable<decimal> 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);
}
/// <summary>
/// Calculate the product of a collection with a selector to translate its items to decimals.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="enumerable"></param>
/// <param name="selector"></param>
/// <returns></returns>
public static decimal Product<T>(this IEnumerable<T> enumerable, Func<T, decimal> 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));
}
}
}
Comments