You need the lambda because that is what the language and framework dictate. Lambdas in this case aren't the short form, but rather the true form.
If something were to be considered the alternative or long form, it would be query syntax.
var customers = (
from cust
in _context.Customers
where cust.Age > 30
).ToList()
This gets translated by the compiler into
var customers = _context.Customers.Where(x => x.Age > 30).ToList();
To address something you hint at, Where
expects a Func<T, bool>
. If you were to leave off the x => x.
and tried to do this:
var customers = _context.Customers.Where(Age > 30).ToList();
You'd get a compiler error as this is not valid syntax, refers to a property not in scope and ultimately passes an expression whose best possible type would be bool
and not Func<T, bool>
A lambda and a function can be interchangeable. In this case the function needs to accept Customer
and return bool
. For example you can have a function OlderThan30
:
public static bool OlderThan30(Customer c)
{
return c.Age > 30;
}
var customers = _context.Customers.Where(x => OlderThan30(x)).ToList();
// or even shorter with a Method Group
var customers = _context.Customers.Where(OlderThan30).ToList();
The function could even take other arguments:
public static bool IsOlderThan(Customer c, int age)
{
return c.Age > age;
}
var customers = _context.Customers.Where(x => IsOlderThan(x, 30)).ToList();
// note method group syntax not valid here
When using Linq2Sql, Entity Framework or other ORMs the Where
method accepts both a Func<T, bool>
and an Expression<Func<T, bool>>
. Expressions and lambdas look the same. The compiler will chose the correct one depending on whether you are working with an IQueryable<T>
or an IEnumerable<T>
. For Linq2Sql/EF it will be the former.
Please note that in both cases (for these examples) the lambda will work properly; the Func
will be executed in memory and the Expression
will be translated to SQL. The function version however will not be translatable to SQL and will either raise an exception or will be performed entirely in memory (depending on the ORM)