If.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Collections.Generic;
  5. namespace System.Linq
  6. {
  7. public static partial class EnumerableEx
  8. {
  9. /// <summary>
  10. /// Returns an enumerable sequence based on the evaluation result of the given condition.
  11. /// </summary>
  12. /// <typeparam name="TResult">Result sequence element type.</typeparam>
  13. /// <param name="condition">Condition to evaluate.</param>
  14. /// <param name="thenSource">Sequence to return in case the condition evaluates true.</param>
  15. /// <param name="elseSource">Sequence to return in case the condition evaluates false.</param>
  16. /// <returns>Either of the two input sequences based on the result of evaluating the condition.</returns>
  17. public static IEnumerable<TResult> If<TResult>(Func<bool> condition, IEnumerable<TResult> thenSource, IEnumerable<TResult> elseSource)
  18. {
  19. if (condition == null)
  20. throw new ArgumentNullException(nameof(condition));
  21. if (thenSource == null)
  22. throw new ArgumentNullException(nameof(thenSource));
  23. if (elseSource == null)
  24. throw new ArgumentNullException(nameof(elseSource));
  25. return Defer(() => condition() ? thenSource : elseSource);
  26. }
  27. /// <summary>
  28. /// Returns an enumerable sequence if the evaluation result of the given condition is true, otherwise returns an empty
  29. /// sequence.
  30. /// </summary>
  31. /// <typeparam name="TResult">Result sequence element type.</typeparam>
  32. /// <param name="condition">Condition to evaluate.</param>
  33. /// <param name="thenSource">Sequence to return in case the condition evaluates true.</param>
  34. /// <returns>The given input sequence if the condition evaluates true; otherwise, an empty sequence.</returns>
  35. public static IEnumerable<TResult> If<TResult>(Func<bool> condition, IEnumerable<TResult> thenSource)
  36. {
  37. if (condition == null)
  38. throw new ArgumentNullException(nameof(condition));
  39. if (thenSource == null)
  40. throw new ArgumentNullException(nameof(thenSource));
  41. return Defer(() => condition() ? thenSource : Enumerable.Empty<TResult>());
  42. }
  43. }
  44. }