gpt4 book ai didi

c# - Where 子句使用表达式 > 和

转载 作者:太空宇宙 更新时间:2023-11-03 10:42:19 24 4
gpt4 key购买 nike

这是我的代码:

public class Person
{
public int Id {get; set;}
public string Name {get; set;}
public Place place {get; set;}
}

public class Customer : Person
{
public int Id {get; set;}
public string CustomerProperty {get; set;}
}

public class Employee : Person
{
public int Id {get; set;}
public string EmployeeProperty {get; set;}
}

所以我创建了一个方法来使用 linq Where 子句按房地产或城市或地点进行过滤。

        public static Expression<Func<Customer, bool>> FilterByPlace(string stateId, string cityId, string placeId)
{
if (placeId != null)
{
return u => u.PlaceId == placeId;
}
else if (cityId != null)
{
return u => u.Place.Address.cod_city == cityId;
}
else if (stateId != null)
{
return u => u.Place.Address.City.cod_state == stateId;
}

return u => true;
}

如果我想为员工执行此操作,我需要复制并更改此 <Func<Customer>><Func<Employee>> .有没有办法使用 <T> in 而不是我的实体?

当我更改 <Func<Person>> 的代码时它返回错误,因为 Type 与 linq 表达式的预期类型不同。

var custom = db.Customers
.Include(item => item.Place)
.Include(item => item.Place.Address)
.Include(item => item.Place.Address.City)
.Include(item => item.Place.Address.City.State)
.Where(item => item.Status == (Status)tableStatus)
.Where(FilterByPlace(stateId, cityId, placeId))
.OrderByDescending(item => item.CustomerId);

谢谢!

最佳答案

尝试创建一个以 Person 作为通用约束的通用方法。

public static Expression<Func<T, bool>> FilterByPlace<T>(string stateId, string cityId, string placeId) 
where T : Person
{
if (placeId != null)
{
return u => u.PlaceId == placeId;
}
else if (cityId != null)
{
return u => u.Place.Address.cod_city == cityId;
}
else if (stateId != null)
{
return u => u.Place.Address.City.cod_state == stateId;
}

return u => true;
}

关于c# - Where 子句使用表达式 <Func<>> 和 <T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24918442/

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