Faraji Anderson Faraji Anderson - 2 months ago 9x
C# Question

Create empty lambda expression

Consider the function:

public async Task<IEnumerable<Purchases>> GetPurchases(User user, Expression<Func<Purchases, bool>> whereClause)
using (var context = new UserDbContext())
context.Entry(user).Collection(p => p.Purchases)

if (Equals(user.Purchases, null))
return new List<Purchases>();

return user.Purchases;

In this function the parameter whereClause can at times be
, I'm wanting to check if its null and then assign an empty Expression if so. This is as close as I've come:

if (Equals(whereClause, null))
whereClause = () => { };

This was based on the question here, but for the line that makes whereClause empty I'm getting the error.

Error 7 Not all code paths return a value in lambda expression of type

Anyone know how this could be corrected?


"Not all code paths return a value" means your lambda isn't returning anything.

Where requires a lambda which takes one parameter, and returns bool. Where won't let you give it an empty lambda expression.

You need to give it something it can use to filter items with.

That's actually easy:

if (Equals(whereClause, null))
   whereClause = o => true;

That's a where clause that always returns true, regardless of what you give it. That's probably what you want: If there's no filter, include everything. For each item in the enumeration, one at a time, Where gives the lambda the item as o. If the lambda returns true, it includes that value of o in the results.

If you want a null filter to return nothing, just return false instead:

if (Equals(whereClause, null))
   whereClause = o => false;