基于组合框值构建动态LINQ查询

基于组合框值构建动态LINQ查询

问题描述:

我在Silverlight中有一个组合框.它具有根据我的LINQ-to-SQL对象之一(即名称,地址,年龄等)的属性构建的值的集合.我想根据组合框中选择的值来过滤结果.

I have a combo box in Silverlight. It has a collection of values built out of the properties of one of my LINQ-to-SQL objects (ie Name, Address, Age, etc...). I would like to filter my results based off the value selected in a combo box.

示例:假设我希望每个人的姓氏为"Smith".我将从下拉列表中选择姓氏",然后将smith输入文本框控件.通常,我会编写类似于...的LINQ查询

Example: Say I want everyone with a last name "Smith". I'd select 'Last Name' from the drop down list and enter smith into a textbox control. Normally I would write a LINQ query similar to...

var query =来自集合中的p
,其中p.LastName ==文本框.文本
选择p;

是否可以动态确定属性,例如使用反射?像

Is it possible to decide the property dynamically, maybe using Reflection? Something like

var query =来自集合中p的
其中p.(DropDownValue)==文本框.文本
选择p;

假设:

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

IQueryable<Person> collection;

您的查询:

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

表示与以下内容相同:

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

Queryable.Where的第二个参数是Expression<Func<Person, bool>>.编译器了解Expression<>类型并生成代码以构建表达式树代表lambda:

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

具有:

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