// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace System.Linq { public static partial class EnumerableEx { /// /// Returns an enumerable sequence based on the evaluation result of the given condition. /// /// Result sequence element type. /// Condition to evaluate. /// Sequence to return in case the condition evaluates true. /// Sequence to return in case the condition evaluates false. /// Either of the two input sequences based on the result of evaluating the condition. public static IEnumerable If(Func condition, IEnumerable thenSource, IEnumerable elseSource) { if (condition == null) throw new ArgumentNullException(nameof(condition)); if (thenSource == null) throw new ArgumentNullException(nameof(thenSource)); if (elseSource == null) throw new ArgumentNullException(nameof(elseSource)); return Defer(() => condition() ? thenSource : elseSource); } /// /// Returns an enumerable sequence if the evaluation result of the given condition is true, otherwise returns an empty /// sequence. /// /// Result sequence element type. /// Condition to evaluate. /// Sequence to return in case the condition evaluates true. /// The given input sequence if the condition evaluates true; otherwise, an empty sequence. public static IEnumerable If(Func condition, IEnumerable thenSource) { if (condition == null) throw new ArgumentNullException(nameof(condition)); if (thenSource == null) throw new ArgumentNullException(nameof(thenSource)); return Defer(() => condition() ? thenSource : Enumerable.Empty()); } } }