If.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. {
  21. throw new ArgumentNullException(nameof(condition));
  22. }
  23. if (thenSource == null)
  24. {
  25. throw new ArgumentNullException(nameof(thenSource));
  26. }
  27. if (elseSource == null)
  28. {
  29. throw new ArgumentNullException(nameof(elseSource));
  30. }
  31. return Defer(() => condition() ? thenSource : elseSource);
  32. }
  33. /// <summary>
  34. /// Returns an enumerable sequence if the evaluation result of the given condition is true, otherwise returns an empty
  35. /// sequence.
  36. /// </summary>
  37. /// <typeparam name="TResult">Result sequence element type.</typeparam>
  38. /// <param name="condition">Condition to evaluate.</param>
  39. /// <param name="thenSource">Sequence to return in case the condition evaluates true.</param>
  40. /// <returns>The given input sequence if the condition evaluates true; otherwise, an empty sequence.</returns>
  41. public static IEnumerable<TResult> If<TResult>(Func<bool> condition, IEnumerable<TResult> thenSource)
  42. {
  43. if (condition == null)
  44. {
  45. throw new ArgumentNullException(nameof(condition));
  46. }
  47. if (thenSource == null)
  48. {
  49. throw new ArgumentNullException(nameof(thenSource));
  50. }
  51. return Defer(() => condition() ? thenSource : Enumerable.Empty<TResult>());
  52. }
  53. }
  54. }