Take the following list:
{
new Person { Name = "Adrian", Age=34 },
new Person { Name = "Lilach", Age=32 },
new Person { Name = "Yuval", Age=5 },
new Person { Name = "Alon", Age=3 },
};
Of the following class:
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
Using LINQ, we can easily select some items using lambda expressions, for example:
{
new Person { Name = "Adrian", Age=34 },
new Person { Name = "Lilach", Age=32 },
new Person { Name = "Yuval", Age=5 },
new Person { Name = "Alon", Age=3 },
};
var selected = persons.Where(p => p.Age > 5 || p.Name.Contains("va"));
And get this result:
The Where method accepts a hard-coded expression and if we want to provide the user the ability to define filters, we have to build the expression at runtime.
In-addition to building the expression at runtime, we have to give the user a proper way to input such an expression.
A simple approach to giving the user the ability to filter the data may be using an SQL syntax, for example:
{
new Person { Name = "Adrian", Age=34 },
new Person { Name = "Lilach", Age=32 },
new Person { Name = "Yuval", Age=5 },
new Person { Name = "Alon", Age=3 },
};
var selected = persons.Where("Age > 5 OR Name LIKE '*va*'");