|
| 1 | +namespace AutSoft.Linq.Enumerable; |
| 2 | + |
| 3 | +/// <summary> |
| 4 | +/// Extensions methods for <see cref="IEnumerable{T}"/> with helper functionality for Where methods |
| 5 | +/// </summary> |
| 6 | +public static class WhereExtensions |
| 7 | +{ |
| 8 | + /// <summary> |
| 9 | + /// Conditionally append a where expression to <see cref="IEnumerable{T}"/> for performance considerations. |
| 10 | + /// </summary> |
| 11 | + /// <typeparam name="TSource">Element's type</typeparam> |
| 12 | + /// <param name="source">An <see cref="IEnumerable{T}" /> to conditionally filter</param> |
| 13 | + /// <param name="condition">Condition to determine which function to use in Where clause</param> |
| 14 | + /// <param name="conditionTruePredicate">Function to use if the <paramref name="condition"/> is true</param> |
| 15 | + /// <param name="conditionFalsePredicate">Optional function to use if the <paramref name="condition"/> is false</param> |
| 16 | + /// <returns><see cref="IEnumerable{T}"/> with filtering expressions.</returns> |
| 17 | + public static IEnumerable<TSource> Where<TSource>( |
| 18 | + this IEnumerable<TSource> source, |
| 19 | + bool condition, |
| 20 | + Func<TSource, bool> conditionTruePredicate, |
| 21 | + Func<TSource, bool>? conditionFalsePredicate = null) |
| 22 | + { |
| 23 | + if (condition) |
| 24 | + { |
| 25 | + return source.Where(conditionTruePredicate); |
| 26 | + } |
| 27 | + else if (conditionFalsePredicate != null) |
| 28 | + { |
| 29 | + return source.Where(conditionFalsePredicate); |
| 30 | + } |
| 31 | + else |
| 32 | + { |
| 33 | + return source; |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + /// <summary> |
| 38 | + /// Conditionally append statements to a <see cref="IEnumerable{T}"/> fluent call chain |
| 39 | + /// in order to keep the fluent syntax |
| 40 | + /// </summary> |
| 41 | + /// <typeparam name="TSource">Element's type</typeparam> |
| 42 | + /// <param name="source">An <see cref="IEnumerable{T}" /> to extend</param> |
| 43 | + /// <param name="condition">Condition to determine transform the source or not</param> |
| 44 | + /// <param name="transform">Function which describes the modifications on the <paramref name="source"/>.</param> |
| 45 | + /// <returns>An extended <see cref="IEnumerable{T}"/></returns> |
| 46 | + public static IEnumerable<TSource> If<TSource>( |
| 47 | + this IEnumerable<TSource> source, |
| 48 | + bool condition, |
| 49 | + Func<IEnumerable<TSource>, IEnumerable<TSource>> transform) |
| 50 | + { |
| 51 | + return condition ? transform(source) : source; |
| 52 | + } |
| 53 | +} |
0 commit comments