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

标签 linq silverlight linq-to-sql dynamic-linq

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

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

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



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

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

编译器将其从扩展方法转换为:
var query = Queryable.Where(collection, p => p.LastName == textBox.Text);
Queryable.Where的第二个参数是Expression<Func<Person, bool>>。编译器了解Expression<>类型并生成代码以构建代表lambda的expression tree:
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"));

这就是查询语法的含义。

您可以自己调用这些方法。要更改比较的属性,请替换为:
typeof(Person).GetProperty("LastName")

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

关于linq - 基于组合框值构建动态LINQ查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/497121/

相关文章:

vb.net - 组加入有多个条件,其中之一是常量

c# - 如何在变量值更改时触发事件?

c# - 无法在 WP7 中使用 webClient.DownloadStringCompleted?

c# - 如何在 Linq to SQL 中使用 distinct 和 group by

C# LINQ & 在部署后添加数据库

c# - 有序区别

C# Linq 对字典列表进行过滤

c# - 从数据库 LinqToSql 访问值的任何更好的方法

linq - Entity Framework 似乎不必要地两次加入同一个表

c# - 如何在 silverlight 中制作垂直自动收报机?