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

源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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;
}

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×