C# Linq where clause as a variable
Solution 1:
You need to assembly an Expression<Func<T, bool>>
and pass it to the Where()
extension method:
Expression<Func<T, bool>> whereClause = a => a.zip == 23456;
var x = frSomeList.Where(whereClause);
EDIT: If you're using LINQ to Objects, remove the word Expression
to create an ordinary delegate.
Solution 2:
This:
var query = from something in someList where whereClause;
is shorthand for:
var query = someList.Where(something => whereClause);
Assuming someList
is an IEnumerable<Address>
, Where
refers to the Enumerable.Where Extension Method. This method expects a Func<Address, bool>
which you can define as follows:
Func<Address, bool> whereClause = address => address.Zip == 23456;
var query = someList.Where(whereClause);