Building Dynamic LINQ Queries based on Combobox Value

Assuming:

public class Person
{
    public string LastName { get; set; }
}

IQueryable<Person> collection;

your query:

var query =
    from p in collection
    where p.LastName == textBox.Text
    select p;

means the same as:

var query = collection.Where(p => p.LastName == textBox.Text);

which the compiler translates from an extension method to:

var query = Queryable.Where(collection, p => p.LastName == textBox.Text);

The second parameter of Queryable.Where is an Expression<Func<Person, bool>>. The compiler understands the Expression<> type and generates code to build an expression tree representing the lambda:

using System.Linq.Expressions;

var query = Queryable.Where(
    collection,
    Expression.Lambda<Func<Person, bool>>(
        Expression.Equal(
            Expression.MakeMemberAccess(
                Expression.Parameter(typeof(Person), "p"),
                typeof(Person).GetProperty("LastName")),
            Expression.MakeMemberAccess(
                Expression.Constant(textBox),
                typeof(TextBox).GetProperty("Text"))),
        Expression.Parameter(typeof(Person), "p"));

That is what the query syntax means.

You are free to call these methods yourself. To change the compared property, replace this:

typeof(Person).GetProperty("LastName")

with:

typeof(Person).GetProperty(dropDown.SelectedValue);

Leave a Comment