WhereIf

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

Description

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

Details

Double click on the code to select all.

 

;