使用 Group By 的 Linq 动态查询

Linq Dynamic Query With Group By

我的 Linq 查询需要额外的 where 子句。例如,如果客户选择一个日期过滤器,那么我需要对我的查询进行日期过滤器等...当我尝试 myQuery.Where 谓词时,只有分组依据的字段可见。

如何将新的 where 条件附加到我的查询中。

//for example i need dynamically append o.OrderDate==Datetime.Now or another where clause

var myQuery =(from o in _db.Orders
join l in _db.OrderLines.Where(x => x.ParaBirimi == model.ParaBirimi) on o.orderId equals
    l.OrderId
where o.OrderDate.Value.Year == year1 
group o by new {o.OrderDate.Value.Month}
into g
select
    new
    {
        Month = g.Key.Month,
        Total = g.Select(t => t.OrderLines.Sum(s => s.OrderTotal)).FirstOrDefault()
    });

您在查询结束时来不及添加新的 Where。您已经对数据进行了分组并对其进行了投影,几乎删除了所有字段。

尝试:

var baseQuery = from o in _db.Orders
                join l in _db.OrderLines.Where(x => x.ParaBirimi == model.ParaBirimi) on o.orderId equals l.OrderId
                where o.OrderDate.Value.Year == year1
                select new { Order = o, OrderLine = l };

if (something)
{
     baseQuery = baseQuery.Where(x => x.Order.Foo == "Bar");
}

var myQuery = (from o in baseQuery
               group o by new { o.Order.OrderDate.Value.Month }
                   into g
                   select
                       new
                       {
                           Month = g.Key.Month,
                           Total = g.Sum(t => t.OrderLine.OrderTotal)
                       });

显然你可以有多个 if。每个 .Where()&& (AND) 与其他条件。

请注意 join 的结果如何投影到具有两个属性的匿名 class 中:OrderOrderLine