If.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Threading.Tasks;
  8. namespace System.Linq
  9. {
  10. public static partial class EnumerableEx
  11. {
  12. /// <summary>
  13. /// Returns an enumerable sequence based on the evaluation result of the given condition.
  14. /// </summary>
  15. /// <typeparam name="TResult">Result sequence element type.</typeparam>
  16. /// <param name="condition">Condition to evaluate.</param>
  17. /// <param name="thenSource">Sequence to return in case the condition evaluates true.</param>
  18. /// <param name="elseSource">Sequence to return in case the condition evaluates false.</param>
  19. /// <returns>Either of the two input sequences based on the result of evaluating the condition.</returns>
  20. public static IEnumerable<TResult> If<TResult>(Func<bool> condition, IEnumerable<TResult> thenSource, IEnumerable<TResult> elseSource)
  21. {
  22. if (condition == null)
  23. throw new ArgumentNullException(nameof(condition));
  24. if (thenSource == null)
  25. throw new ArgumentNullException(nameof(thenSource));
  26. if (elseSource == null)
  27. throw new ArgumentNullException(nameof(elseSource));
  28. return Defer(() => condition() ? thenSource : elseSource);
  29. }
  30. /// <summary>
  31. /// Returns an enumerable sequence if the evaluation result of the given condition is true, otherwise returns an empty
  32. /// sequence.
  33. /// </summary>
  34. /// <typeparam name="TResult">Result sequence element type.</typeparam>
  35. /// <param name="condition">Condition to evaluate.</param>
  36. /// <param name="thenSource">Sequence to return in case the condition evaluates true.</param>
  37. /// <returns>The given input sequence if the condition evaluates true; otherwise, an empty sequence.</returns>
  38. public static IEnumerable<TResult> If<TResult>(Func<bool> condition, IEnumerable<TResult> thenSource)
  39. {
  40. if (condition == null)
  41. throw new ArgumentNullException(nameof(condition));
  42. if (thenSource == null)
  43. throw new ArgumentNullException(nameof(thenSource));
  44. return Defer(() => condition() ? thenSource : Enumerable.Empty<TResult>());
  45. }
  46. }
  47. }