Я знаю, как построить простую лямбду, такую как x => x> 5 :
int[] nbs = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
IEnumerable<int> result1 = nbs.Where(x => x > 5);
ParameterExpression parameter = Expression.Parameter(typeof(int), "x");
ConstantExpression constant = Expression.Constant(5);
BinaryExpression expressionBody = Expression.GreaterThan(parameter, constant);
Expression<Func<int, bool>> expression = Expression.Lambda<Func<int, bool>>(expressionBody, parameter);
IEnumerable<int> result2 = nbs.Where(expression.Compile());
Но как мне построить лямбду следующим образом p => p.Cars.Any (c => c.Horsepowers> 300) ?
public class Person
{
public string Name { get; set; }
public List<Car> Cars { get; set; }
}
public class Car
{
public string Make { get; set; }
public int Horsepowers { get; set; }
}
Person p1 = new Person();
p1.Name = "Thom";
p1.Cars = new List<Car>()
{
new Car(){Horsepowers = 100, Make = "Toyota"},
new Car(){Horsepowers = 200, Make = "Fiat"},
new Car(){Horsepowers = 300, Make = "Audi"},
new Car(){Horsepowers = 400, Make = "Ferrari"}
};
Person p2 = new Person();
p2.Name = "Allen";
p2.Cars = new List<Car>()
{
new Car(){Horsepowers = 500, Make = "McLaren"},
new Car(){Horsepowers = 200, Make = "Volvo"},
new Car(){Horsepowers = 300, Make = "Audi"},
new Car(){Horsepowers = 400, Make = "Ferrari"}
};
List<Person> persons = new List<Person>();
persons.Add(p1);
persons.Add(p2);
IEnumerable<Person> res = persons.Where(p => p.Cars.Any(c => c.Horsepowers > 300));
Другими словами, как динамически построить выражение (Expression<Func<Person, bool>>
), которое я могу передать в качестве параметра методу Where?