gpt4 book ai didi

c# - 使用连接但条件不同的相同 LINQ 查询

转载 作者:太空狗 更新时间:2023-10-30 00:32:59 25 4
gpt4 key购买 nike

我有一些非常相似的 LINQ 查询:

var city = "Hamburg";

var query1 =
from c in DB.Customers
join address in DB.Addresses on c.ID equals address.CustomerID
where address.City == city
select c;

var query2 =
from c in DB.Customers
join address in DB.Addresses on c.ID equals address.CustomerID
where address.City.StartsWith(city)
select c;

etc.

我想使用循环来创建查询以减少冗余:

var city = "Hamburg";

var expressions = new Expression<Func<string, bool>>[] {
a => a == city,
a => a.StartsWith(city)
};

for(int i = 1; i <= 2; i++) {
queries.Add(
from c in DB.Customers
join address in DB.Addresses on c.ID equals address.CustomerID
where expressions[i](address.City)
select c
);
}

但我现在不知道如何创建表达式数组。有什么想法吗?

最佳答案

var city = "Hamburg";

// predicate should accept Address
var expressions = new Expression<Func<Address, bool>>[] {
a => a.City == city,
a => a.City.StartsWith(city)
};

foreach(var predicate in expressions) {
queries.Add(
DB.Customers.Join(
DB.Addresses.Where(predicate), // filtering here
c => c.ID,
a => a.CustomerID,
(c, a) => c) // return customer
));
}

关于c# - 使用连接但条件不同的相同 LINQ 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14236104/

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