Advertisement
jhenriquecosta

collection.extensions

Oct 28th, 2021
903
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.28 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. namespace Works.Collections.Extensions
  5. {
  6.     /// <summary>
  7.     /// Extension methods for Collections.
  8.     /// </summary>
  9.     public static class CollectionExtensions
  10.     {
  11.         /// <summary>
  12.         /// Checks whatever given collection object is null or has no item.
  13.         /// </summary>
  14.         public static bool IsNullOrEmpty<T>(this ICollection<T> source)
  15.         {
  16.             return source == null || source.Count <= 0;
  17.         }
  18.  
  19.         /// <summary>
  20.         /// Adds an item to the collection if it's not already in the collection.
  21.         /// </summary>
  22.         /// <param name="source">Collection</param>
  23.         /// <param name="item">Item to check and add</param>
  24.         /// <typeparam name="T">Type of the items in the collection</typeparam>
  25.         /// <returns>Returns True if added, returns False if not.</returns>
  26.         public static bool AddIfNotContains<T>(this ICollection<T> source, T item)
  27.         {
  28.             if (source == null)
  29.             {
  30.                 throw new ArgumentNullException("source");
  31.             }
  32.  
  33.             if (source.Contains(item))
  34.             {
  35.                 return false;
  36.             }
  37.  
  38.             source.Add(item);
  39.             return true;
  40.         }
  41.     }
  42. }
  43.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement