基于Combobox值构建动态LINQ查询

Ste*_* G. 9 linq silverlight dynamic-linq linq-to-sql

我在Silverlight中有一个组合框.它有一个由我的一个LINQ-to-SQL对象(即Name,Address,Age等)的属性构建的值集合.我想根据组合框中选择的值过滤我的结果.

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

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

是否可以动态决定属性,也许使用Reflection?就像是

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

Bry*_*tts 19

假设:

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

IQueryable<Person> collection;
Run Code Online (Sandbox Code Playgroud)

您的查询:

var query =
    from p in collection
    where p.LastName == textBox.Text
    select p;
Run Code Online (Sandbox Code Playgroud)

意思是:

var query = collection.Where(p => p.LastName == textBox.Text);
Run Code Online (Sandbox Code Playgroud)

编译器从扩展方法转换为:

var query = Queryable.Where(collection, p => p.LastName == textBox.Text);
Run Code Online (Sandbox Code Playgroud)

第二个参数Queryable.WhereExpression<Func<Person, bool>>.编译器理解Expression<>类型并生成代码以构建表示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"));
Run Code Online (Sandbox Code Playgroud)

这就是查询语法的含义.

您可以自己调用这些方法.要更改比较属性,请替换为:

typeof(Person).GetProperty("LastName")
Run Code Online (Sandbox Code Playgroud)

有:

typeof(Person).GetProperty(dropDown.SelectedValue);
Run Code Online (Sandbox Code Playgroud)