有没有更好的方法来编写这个Linq查询

时间:2011-02-15 15:52:07

标签: linq conditional where-clause

实施例

from O in db.Orders
join C in db.Customers on C.Id equals O.CustID
Where O.ord_date == ( filter.OrderDate != null ? filter.OrderDate : o.ord_date) &&
  c.Id == (filter.CustId != null ? filter.CustId : c.Id) &&
  o.ProductId == ( filter.ProductId != null ? filter.ProductId : o.ProductID)
select new {o,c}

//select new {c.Name, C.JoinDate, O.Value, O.NoofLineItems }

当我在配置文件上运行时,它有很多案例陈述,正如我所希望的那样。但是我对C#中放入的条件有了更多的控制权,我怎么能在where条件下运行我的控制权,只有当过滤器可用时才放置where条件

这将提高我的db的质量。

亲切的问候 维奈。

3 个答案:

答案 0 :(得分:2)

此类问题的一般解决方案是使用PredicateBuilder动态构建相应的谓词。

首先,构建谓词:

Expression<Func<Order, bool>> predicate = PredicateBuilder.True<Order>();

if (filter.OrderDate != null)
    predicate = predicate.And(o => o.ord_date == filter.OrderDate);

if (filter.CustId != null)
    predicate = predicate.And(o => o.CustId == filter.CustId);

...

然后你的查询变为:

var filtered = db.Orders.Where(predicate);

var query = from O in filtered 
            join C in db.Customers on C.Id equals O.CustID
            select new {o,c};      

答案 1 :(得分:2)

鉴于条件不依赖于查询,您可以从查询中获取条件并逐渐构建它:

var query = from o in db.Orders
            join c in db.Customers on c.Id equals o.CustID
            select new {o,c};
if(filter.OrderDate != null)
{
    query = query.Where(x => x.o.ord_date == filter.OrderDate);
}
if(filter.CustId != null)
{
    query = query.Where(x => x.c.Id == filter.CustId);
}
if(filter.ProductId != null)
{
    query = query.Where(x => x.o.ProductID == filter.ProductId);
}

答案 2 :(得分:0)

也许改成它:

from O in db.Orders
join C in db.Customers on C.Id equals O.CustID
Where O.ord_date == ( filter.OrderDate ?? o.ord_date) &&
  c.Id == (filter.CustId ?? c.Id) &&
  o.ProductId == (filter.ProductId ?? o.ProductID)
select new {o,c}

使用?? operator可以让事情变得更加整洁。它基本上就像是.NET的合并运算符

除此之外,我不确定你还能改变什么。