Compose LINQ-to-SQL predicates into a single predicate

后端 未结 2 957
感情败类
感情败类 2021-02-09 23:02

(An earlier question, Recursively (?) compose LINQ predicates into a single predicate, is similar to this but I actually asked the wrong question... the solution there satisfied

2条回答
  •  余生分开走
    2021-02-09 23:41

    Normally you would chain invocations of .Where(...). E.g.:

    var a = dataContext.Customers;
    if (kwd1 != null)
        a = a.Where(t => t.Customer.Forenames.Contains(kwd1));
    if (kwd2 != null)
        a = a.Where(t => t.Customer.Forenames.Contains(kwd2));
    // ...
    return a;
    

    LINQ-to-SQL would weld it all back together into a single WHERE clause.

    This doesn't work with OR, however. You could use unions and intersections, but I'm not sure whether LINQ-to-SQL (or SQL Server) is clever enough to fold it back to a single WHERE clause. OTOH, it won't matter if performance doesn't suffer. Anyway, it would look something like this:

     ff = null, ss = null;
    
    foreach (k in keywords) {
        if (keywords != null) {
            var f = dataContext.Customers.Where(t => t.Customer.Forenames.Contains(k));
            ff = ff == null ? f : ff.Union(f);
    
            var s = dataContext.Customers.Where(t => t.Customer.Surname.Contains(k));
            ss = ss == null ? s : ss.Union(s);
        }
    }
    return ff.Intersect(ss);
    

提交回复
热议问题