Linq声明订单报告

时间:2016-03-17 18:23:56

标签: c# linq

我的数据库中有订单,每个订单都有一系列的免税额。与订单相关的限额有一个ChargeIndicator来表示它是否为折扣(0)或不是(1)。

在一段时间内,我需要在此期间使用的折扣,以及使用每次折扣的订单总和。

我可以获取已使用折扣的列表,但我无法返回订单以获取聚合

var discounts = this.Repository.GetOrders()
            .Where(o => 
                o.AllowanceCharge.Any(ac => !ac.ChargeIndicator) &&
                o.IssueDate > DateTime.Now.AddDays(-10) &&
                o.IssueDate < DateTime.Now.AddDays(-1))
            .SelectMany(o => o.AllowanceCharge.Where(ac => !ac.ChargeIndicator))
            .Discinct()

3 个答案:

答案 0 :(得分:0)

为简单起见,我可能只是在两次往返中这样做:

var ordersWithDiscounts = this.Repository.GetOrders()
    .Where(o => 
        o.AllowanceCharge.Any(ac => !ac.ChargeIndicator) &&
        o.IssueDate > DateTime.Now.AddDays(-10) &&
        o.IssueDate < DateTime.Now.AddDays(-1));
var sumOfOrdersWithDiscounts = ordersWithDiscounts.Sum(o => o.TotalCostOrWhatever);
var discounts = ordersWithDiscounts
    .SelectMany(o => o.AllowanceCharge.Where(ac => !ac.ChargeIndicator))
    .ToList();

答案 1 :(得分:0)

最简单的方法是对关系数据进行去规范化,然后对数据应用聚合。

   // filter the allowance applied orders
   var filtered = GetOrders().Where(x => x.AllowanceCharge.Any(t => t.ChargeIndicator));

   // Flat the relations data
   var denormalized =
           from order in filtered
           join allowance in filtered.SelectMany(x => x.AllowanceCharge) on order.Id equals allowance.OrderId
           select new { order = order.Name, alName = allowance.Name };

   // groupt it

   var result = denormalized.GroupBy(info => info.alName)
               .Select(group => new
               {
                   Allowance = group.Key,
                   OrderCount = group.Count()
               });

使用Lambda表达式组合士气低落和groupby,

 var result =
 filtered.Join(filtered.SelectMany(x => x.AllowanceCharge), 
               order => order.Id, allowance => allowance.OrderId,
               (order, allowance) => new { order = order.Name, allowance = allowance.Name })
         .GroupBy(record => record.allowance)
         .Select(group => new
            {
                Allowance = group.Key,
                OrderCount = group.Count()
            });

结果 -

{ Allowance = A, OrderCount = 3 }
{ Allowance = C, OrderCount = 1 }
{ Allowance = B, OrderCount = 1 }

答案 2 :(得分:0)

我认为这就是你想要的(如果你想在1个查询中全部使用):

this.Repository.GetOrders()
    .Where(o => o.IssueDate > DateTime.Now.AddDays(-10) &&
                o.IssueDate < DateTime.Now.AddDays(-1))
    .SelectMany(o => o.AllowanceCharge
        .Where(ac => !ac.ChargeIndicator)
        .Select(ac => new { order = o, charge = ac}))
    .GroupBy(_ => _.charge.Id)
    .Select(grp => new
    {
        AllowanceChargeId = grp.Key,
        OrdersForThisCharge = grp.Select(_ => _.order)
    });