For me this happened when I need to Chaining query operators, for example you have a list of categories to filter your return data. I want to look at homes from New York, California and Florida.
What is Expression<Func<T>>?
Expression<Func<T>> or Expression
So lets look at some code for my example above, find homes in New York, California and Florida.
public HttpResponseMessage Post([FromBody]SearchParams searchParams)
List<Homes> homesList = new List<Homes>();
if (searchParams != null)
using (var ctx = new HomesContext())
homesList = ctx.Homes.Where(FilterByLocations(searchParams.locations)).ToList();
return Request.CreateResponse(HttpStatusCode.OK, homesList);
private Expression<Func<Homes, bool>> _nullCriteriaExpression = p => true;
private Expression<Func<Homes, bool>> FilterByLocations(List<string> locations)
return locations.Count == 0 ? _nullCriteriaExpression : x => locations.Any(y => x.WorkforceDevelopmentAreaName.Contains(y));
A few things to note
- I am passing in a object of type SearchParams, which as a List
- The example uses Entity Framework which you see in the HomesContext
- The _nullCriteriaExpression is for when there is nothing to match, just return true. Like when the list is empty.
- FilterByLocations check each row that is returned from the HomesContext x, against the list of locations y.
A few things to note on the differences between Func
Func<T> is just a normal old-school MulticastDelegate;
Expression<Func<T>> is a representation of lambda expression in form of expression tree;
IEnumerable works with Func and IQueryable works with Expression<Func>
expression tree can be constructed through lambda expression syntax;
expression tree can be compiled to a delegate Func<T>
expression tree can be observed/translated/modified through the ExpressionVisitor;
the extension methods for IEnumerable operate with Func<T>
the extension methods for IQueryable operate with Expression<Func<T>>