I'm trying to combine two lambda expressions to build something with an OR-clause, but it fails with the following exception message:
variable 'foo' of type 'Foo' referenced from scope '', but it is not defined.
Why, and how do I fix it?
Here's a failing code sample, based on Marc Gravell's answer to the question linked above:
static Expression<Func<T, bool>> Or<T>(Expression<Func<T, bool>> a, Expression<Func<T, bool>> b)
=> Expression.Lambda<Func<T, bool>>(Expression.OrElse(a.Body, b.Body), b.Parameters);
static Expression<Func<Foo, bool>> BarMatches(Bar bar) => foo => foo.Bar.Value == bar.Value;
static Expression<Func<Foo, bool>> BazMatches(Baz baz) => foo => foo.Baz.Value == baz.Value;
// sample usage (see below): foos.Where(Or(MatchesBar(bar), MatchesBaz(baz)))
void Main()
{
var foos = new[]
{
new Foo
{
Bar = new Bar
{
Value = "bar"
},
Baz = new Baz
{
Value = "baz"
}
},
new Foo
{
Bar = new Bar
{
Value = "not matching"
},
Baz = new Baz
{
Value = "baz"
}
}
}.AsQueryable();
var bar = new Bar { Value = "bar" };
var baz = new Baz { Value = "baz" };
Console.WriteLine(foos.Where(Or(BarMatches(bar), BazMatches(baz))).Count());
}
// Define other methods and classes here
class Foo
{
public Bar Bar { get; set; }
public Baz Baz { get; set; }
}
class Bar
{
public string Value { get; set; }
}
class Baz
{
public string Value { get; set; }
}