Using Combobox Values to Create Dynamic LINQ Queries

dynamic-linq linq linq-to-sql silverlight

Question

Silverlight contains a combo box I have. It contains a set of values constructed from one of my LINQ-to-SQL objects' attributes (ie Name, Address, Age, etc...). I want to use the value chosen in a combo box to filter my results.

Let's use the example of wanting everyone with the last name Smith. From the drop-down menu, I would choose "Last Name," then type "Smith" into the textbox control. Normally, I'd create a LINQ query that looked like...

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

Can the attribute be determined dynamically, maybe through reflection? something similar

var query = from p in collection
where p.(DropDownValue) == textbox.Text
select p;

1
9
10/5/2009 5:13:40 AM

Accepted Answer

Assuming:

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

IQueryable<Person> collection;

your question

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

equivalent to:

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

which an extension method is translated to by the compiler

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

The second component ofQueryable.Where is anExpression<Func<Person, bool>> . The compiler is aware of theExpression<> creates code for a tree of expression representation of the lambda by typing:

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"));

The query syntax indicates this.

These are approaches that you are free to use. Replace this to modify the compared property:

typeof(Person).GetProperty("LastName")

with:

typeof(Person).GetProperty(dropDown.SelectedValue);
19
1/31/2009 4:58:54 AM

Popular Answer

A brief series on dynamically created LINQ to SQL queries is available from Scott Guthrie:

http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

That is the simple method; however, there is also a little more complex method:

http://www.albahari.com/nutshell/predicatebuilder.aspx



Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow