EnumerableExtensions.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. namespace Wayne.Lib
  5. {
  6. /// <summary>
  7. /// Various extension methods for Enumerables.
  8. /// </summary>
  9. public static class EnumerableExtensions
  10. {
  11. /// <summary>
  12. /// Apply an action for each item in an enumerable.
  13. /// </summary>
  14. /// <typeparam name="T"></typeparam>
  15. /// <param name="enumerable"></param>
  16. /// <param name="action"></param>
  17. public static void ForEach<T>(this IEnumerable<T> enumerable, Action<T> action)
  18. {
  19. foreach (var item in enumerable)
  20. {
  21. action(item);
  22. }
  23. }
  24. /// <summary>
  25. /// Checks wether a given value is contained in an array of values. Similar to
  26. /// Linq Contains, but the readability of the code is different (Better) depending on the domain.
  27. /// </summary>
  28. /// <typeparam name="T"></typeparam>
  29. /// <param name="value"></param>
  30. /// <param name="values"></param>
  31. /// <returns></returns>
  32. public static bool IsIn<T>(this T value, params T[] values)
  33. {
  34. return values.Contains(value);
  35. }
  36. /// <summary>
  37. /// Returns a sequence that is guaranteed to not be null and not contain null values.
  38. /// </summary>
  39. /// <typeparam name="T"></typeparam>
  40. /// <param name="enumerable"></param>
  41. /// <returns>Returns all not null items or an empty IEnumerable</returns>
  42. public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T> enumerable)
  43. {
  44. if (enumerable == null)
  45. return new T[] {};
  46. return enumerable.Where(x=> x != null);
  47. }
  48. }
  49. }