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

标签 c# linq

我有一些非常相似的 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/

相关文章:

c# - 使用 count() 优化 linq 查询

c# - Linq to CSV : Convert data to . CSV 文件并从操作返回文件而不在服务器上保存文件

c# - 为什么 C# CreateObject 比 VB.NET 冗长得多?

c# - 尝试用参数计算一个简单的 gpa 程序

Linq 查询获取 Child 的 Child 记录

vb.net - LINQ 选择新建

c# - 避免在 LINQ orderby 中被零除

c# - 几秒钟后如何触发事件?

c# - 防止 Microsoft OData 客户端请求完整元数据

c# - Entity Framework 6 Code First 中的表重叠数据库上下文