feat: add Enumerable.ConditionalWhere

This commit is contained in:
Kyle Ratti 2022-09-23 21:08:00 -04:00
parent ea050f098a
commit f3f511ad36
No known key found for this signature in database
GPG Key ID: 321BA8EB09CD93F4
2 changed files with 10 additions and 2 deletions

View File

@ -1,4 +1,4 @@
using System.Linq;
using System.Linq;
using FruityFoundation.Base.Extensions;
using NUnit.Framework;
@ -10,4 +10,9 @@ public class EnumerableExtensionTests
[TestCase(new object[] { "hi" }, false, new object[] { "there" }, ExpectedResult = new object[] { "hi" })]
public object[] TestConditionalConcat(object[] input, bool isConditionValid, object[] second) =>
input.ConditionalConcat(isConditionValid, second).ToArray();
[TestCase(new object[] { 0, 1, 2 }, true, 85, ExpectedResult = new object[0])]
[TestCase(new object[] { "hi", "there" }, false, "there", ExpectedResult = new object[] { "hi", "there" })]
public object[] TestConditionalWhere(object[] input, bool isConditionValid, object valueToKeep) =>
input.ConditionalWhere(isConditionValid, x => x.Equals(valueToKeep)).ToArray();
}

View File

@ -1,7 +1,10 @@
namespace FruityFoundation.Base.Extensions;
namespace FruityFoundation.Base.Extensions;
public static class EnumerableExtensions
{
public static IEnumerable<T> ConditionalConcat<T>(this IEnumerable<T> enumerable, bool isConditionValid, IEnumerable<T> second) =>
!isConditionValid ? enumerable : enumerable.Concat(second);
public static IEnumerable<T> ConditionalWhere<T>(this IEnumerable<T> enumerable, bool isConditionValid, Func<T, bool> pred) =>
!isConditionValid ? enumerable : enumerable.Where(pred);
}