gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:04:10 24 4
gpt4 key购买 nike

我在 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<>键入并生成代码以构建 expression tree代表 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"));

这就是查询语法的意思。

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

typeof(Person).GetProperty("LastName")

与:

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

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com