使用联接但条件不同的相同LINQ查询

  • 本文关键字: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
    ));
}

您可以直接使用Join方法,而不是使用查询语法:

public IQueryable<Customer> FindCustomers(Expression<Func<Customer, Address, bool>> predicate)
{
    return DB.Customers.Join(DB.Addresses, c => c.ID, a => d.CustomerID, (c, a) => new { Address = a, Customer = c})
        .Where(pair => predicate(pair.Address))
        .Select(pair => pair.Customer)
}

或者你可以通过CustomerAddress:

public IQueryable<Customer> FindCustomers(Expression<Func<Customer, Address, bool>> predicate)
{
    return DB.Customers.Join(DB.Addresses, c => c.ID, a => d.CustomerID, (c, a) => new { Address = a, Customer = c})
        .Where(pair => predicate(pair.Customer, pair.Address))
        .Select(pair => pair.Customer)
}

然后你可以创建你的阵列为:

IQueryable<Customer>[] queries = expressions.Select(expr => FindCustomers(expr)).ToArray();

您可以在公共查询中保存公共联接部分。

var query = from c in DB.Customers
         join address from DB.Addresses on c.ID equals address.CustomerID
         select new {A=a, C=c};
var query1 = query.Where ( item => item.A.temp == item.C.test).Select (item => item.C);
var query2 = query.Where ( item => item.A.temp2 == item.C.test2).Select (item => item.C);
var queries=(
    from f in
        new Func<Address, bool>[] { 
            x => x.City==city, 
            x => x.City.StartsWith(city)
            }
    select
        from c in DB.Customers
        join address in DB.Addresses on c.ID equals address.CustomerID
        where f(address)
        select c
    ).ToArray();
  1. 你正在创建一个expression array,这意味着你最终得到的是一个expression array;您不需要将代理人设为expression array

  2. 您不需要foreach

  3. 如果稍后将向queries添加更多表达式,则将ToArray()更改为ToList()

  4. 如果您想在生成queries之前修改Func<Address, bool>,那么为其定义一个局部变量,只需替换Func<Address, bool>[]

相关内容

  • 没有找到相关文章

最新更新