gpt4 book ai didi

c# - 使用表达式创建带有嵌套类的谓词

转载 作者:太空狗 更新时间:2023-10-29 20:59:01 26 4
gpt4 key购买 nike

我有这个:

public class Company
{
public int Id { get; set; }
public string Name { get; set; }
}
public class City
{
public int Id { get; set; }
public string Name { get; set; }
public int ZipCode { get; set; }
}
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int? Age { get; set; }
public City City { get; set; }
public Company Company { get; set; }
}

我希望在某些情况下生成这样的谓词:

var result = listPerson.Where(x => x.Age == 10).ToList<>();

或者这个:

var result  = listPerson.Where( x => x.Company.Name == 1234).ToList();

或者这个:

var result  = listPerson.Where( x => x.City.ZipCode == "MyZipCode").ToList();

或者这个:

var result  = listPerson.Where( x => x.Company.Name == "MyCompanyName").ToList();

然后我创建了一个“PredicateBuilder”,这是有效的(我得到类型,如果可以为 null 或不能为 null,然后我构建谓词)当我这样做时:

BuildPredicate<Person>("Age", 10); I get this : x => x.Age == 10

但是当有这样的嵌套属性时,我不知道如何管理:

BuildPredicate<Person>("City.ZipCode", "MyZipCode"); 
I'd like get this : x => x.City.ZipCode == "MyZipCode"

或者这个:

BuildPredicate<Person>("City.Name", "MyName"); 
I'd like get this : x => x.City.Name == "MyName"

或者这个:

BuildPredicate<Person>("Company.Name", "MyCompanyName"); 
I'd like get this : x => x.Company.Name == "MyCompanyName"

最佳答案

(无意复制 Jon - OP 联系我提供答案)

以下似乎工作正常:

static Expression<Func<T,bool>> BuildPredicate<T>(string member, object value) {
var p = Expression.Parameter(typeof(T));
Expression body = p;
foreach (var subMember in member.Split('.')) {
body = Expression.PropertyOrField(body, subMember);
}
return Expression.Lambda<Func<T, bool>>(Expression.Equal(
body, Expression.Constant(value, body.Type)), p);
}

这与 Jon 的回答之间唯一的功能区别是它通过告诉 Expression.Constant 预期类型是什么来更好地处理 null slightly是。作为用法演示:

static void Main() {
var pred = BuildPredicate<Person>("City.Name", "MyCity");

var people = new[] {
new Person { City = new City { Name = "Somewhere Else"} },
new Person { City = new City { Name = "MyCity"} },
};
var person = people.AsQueryable().Single(pred);
}

关于c# - 使用表达式创建带有嵌套类的谓词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14258881/

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