我在 Silverlight 中有一个组合框。 它有一组根据我的 LINQ-to-SQL 对象的属性(即名称、地址、年龄等)构建的值。 我想根据组合框中选择的值过滤结果。
示例:假设我希望每个人的姓氏都是“史密斯”。 我从下拉列表中选择“姓氏”,然后在文本框控件中输入 smith。 通常我会编写一个类似以下的 LINQ 查询...
var query = 来自集合中的 p
其中 p.LastName == textbox.Text
选择 p;
是否可以使用反射动态决定属性? 就像是
var query = 来自集合中的 p
其中 p.(DropDownValue) == textbox.Text
选择 p;
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.
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;
发布评论
评论(3)
假设:
您的查询:
与
编译器从扩展方法转换为:
Queryable.Where
的第二个参数是Expression>< /代码>。 编译器理解
Expression<>
类型并生成代码来构建 表示 lambda 的表达式树:这就是查询语法的含义。
您可以自己调用这些方法。 要更改比较属性,请将其替换
为:
Assuming:
your query:
means the same as:
which the compiler translates from an extension method to:
The second parameter of
Queryable.Where
is anExpression<Func<Person, bool>>
. The compiler understands theExpression<>
type and generates code to build an expression tree representing the lambda:That is what the query syntax means.
You are free to call these methods yourself. To change the compared property, replace this:
with:
Scott Guthrie 有一个关于动态构建 LINQ to SQL 查询的简短系列:
http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the- linq-dynamic-query-library.aspx
这是最简单的方法...然后还有另一种更复杂的方法:
http://www.albahari.com/nutshell/predicatebuilder.aspx
Scott Guthrie has a short series on dyamically built LINQ to SQL queries:
http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
That's the easy way...then there's another way that's a bit more involved:
http://www.albahari.com/nutshell/predicatebuilder.aspx
您还可以使用我创建的库: http://tomasp.net/blog/dynamic -linq-queries.aspx。 您可以将属性作为 lambda 表达式存储在 ComboBox 中,然后只需编写:
You can also use the library I created: http://tomasp.net/blog/dynamic-linq-queries.aspx. You would store the properties in ComboBox as lambda expressions and then just write: