ExtensionMethod.NET Home of 875 C#, Visual Basic, F# and Javascript extension methods

WhereIf

When building a LINQ query, you may need to involve optional filtering criteria. Avoids if statements when building predicates & lambdas for a query. Useful when you don't know at compile time whether a filter should apply. Borrowed from Andrew Robinson. http://bit.ly/1V36G9

Source

public static IEnumerable<TSource> WhereIf<TSource>(this IEnumerable<TSource> source, bool condition, Func<TSource, bool> predicate)
{
    if (condition)
        return source.Where(predicate);
    else
        return source;
}

public static IEnumerable<TSource> WhereIf<TSource>(this IEnumerable<TSource> source, bool condition, Func<TSource, int, bool> predicate)
{
    if (condition)
        return source.Where(predicate);
    else
        return source;
}

Example

List<Customer> custs = new List<Customer>{
new Customer {FirstName = "Peggy", AcctBalance = 12442.98},
new Customer {FirstName = "Sally", AcctBalance = 32.39},
new Customer {FirstName = "Billy", AcctBalance = 25.33},
new Customer {FirstName = "Tommy", AcctBalance = 12345}
};

bool showAccountBalancesUnder5000 = false;

var custList = custs.WhereIf(showAccountBalancesUnder5000, c=>c.AcctBalance < 5000).ToList(); //will not perform the filtering

showAccountBalancesUnder5000 = true;

var custListUnder5000 = custs.WhereIf(showAccountBalancesUnder5000, c=>c.AcctBalance < 5000).ToList(); //will perform the filtering

Author: Phil Campbell

Submitted on: 17 nov 2009

Language: C#

Type: System.Collections.Generic.IEnumerable<T>

Views: 39582