我在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/