基于 Combobox 值构建动态 LINQ 查询 [英] Building Dynamic LINQ Queries based on Combobox Value

查看:18
本文介绍了基于 Combobox 值构建动态 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 = from p in collection
where p.LastName == textbox.Text
select p;

是否可以动态决定属性,也许使用反射?类似的东西

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

var query = from p in collection
where p.(DropDownValue) == textbox.Text
select 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>.编译器理解 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);

这篇关于基于 Combobox 值构建动态 LINQ 查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆