build out dynamic query in csharp

Building a dynamic query in C# involves the use of expression trees to build and execute queries at runtime. Here's a basic example of how to build a dynamic query that filters a list of objects based on a specified property and value:

main.cs
public IEnumerable<T> FilterList<T>(IEnumerable<T> list, string property, object value)
{
    var param = Expression.Parameter(typeof(T), "x");
    var prop = Expression.Property(param, property);
    var val = Expression.Constant(value);
    var equal = Expression.Equal(prop, val);
    var lambda = Expression.Lambda<Func<T, bool>>(equal, param);

    return list.Where(lambda.Compile());
}
393 chars
11 lines

Here's how you can use the function to filter a list of Person objects based on their Age property:

main.cs
var people = new List<Person>
{
    new Person { Name = "Alice", Age = 25 },
    new Person { Name = "Bob", Age = 30 },
    new Person { Name = "Charlie", Age = 35 }
};

var filteredPeople = FilterList(people, "Age", 30);
222 chars
9 lines

The resulting filteredPeople list will contain only the Person object with an Age of 30.

Note that this is just a basic example, and you can modify the FilterList function to handle more complex queries using additional expression tree operations such as AndAlso and OrElse.

gistlibby LogSnag