d3ullist

EnumerableExtensions

Jul 13th, 2021
965
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.34 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace Shared.Extensions
  8. {
  9.     public static class EnumerableExtensions
  10.     {
  11.         /// <summary>
  12.         /// Determines whether the collection is null or contains no elements.
  13.         /// </summary>
  14.         /// <typeparam name="T">The IEnumerable type.</typeparam>
  15.         /// <param name="enumerable">The enumerable, which may be null or empty.</param>
  16.         /// <returns>
  17.         ///     <c>true</c> if the IEnumerable is null or empty; otherwise, <c>false</c>.
  18.         /// </returns>
  19.         /// <source>https://stackoverflow.com/a/8582374/2030635</source>
  20.         public static bool IsNullOrEmpty<T>(this IEnumerable<T> enumerable)
  21.         {
  22.             if (enumerable == null)
  23.             {
  24.                 return true;
  25.             }
  26.             /* If this is a list, use the Count property for efficiency.
  27.              * The Count property is O(1) while IEnumerable.Count() is O(N). */
  28.             if (enumerable is ICollection<T> collection)
  29.             {
  30.                 return collection.Count < 1;
  31.             }
  32.             return !enumerable.Any();
  33.         }
  34.  
  35.         /// <summary>
  36.         /// Calculate the product of a collection of decimals.
  37.         /// </summary>
  38.         /// <param name="enumerable"></param>
  39.         /// <returns></returns>
  40.         public static decimal Product(this IEnumerable<decimal> enumerable)
  41.         {
  42.             //Product of empty collection is 1: https://en.wikipedia.org/wiki/Empty_product
  43.             if (!enumerable.Any()) return 1M;
  44.  
  45.             return enumerable.Aggregate((d1, d2) => d1 * d2);
  46.         }
  47.  
  48.         /// <summary>
  49.         /// Calculate the product of a collection with a selector to translate its items to decimals.
  50.         /// </summary>
  51.         /// <typeparam name="T"></typeparam>
  52.         /// <param name="enumerable"></param>
  53.         /// <param name="selector"></param>
  54.         /// <returns></returns>
  55.         public static decimal Product<T>(this IEnumerable<T> enumerable, Func<T, decimal> selector)
  56.         {
  57.             //Product of empty collection is 1: https://en.wikipedia.org/wiki/Empty_product
  58.             if (!enumerable.Any()) return 1M;
  59.  
  60.             return enumerable.Aggregate(1M, (s, i2) => s * selector(i2));
  61.         }
  62.     }
  63. }
  64.  
Advertisement
Add Comment
Please, Sign In to add comment