Linq查询需要正确的总和

时间:2012-02-22 14:55:52

标签: c# linq linq-to-sql c#-4.0

我正在使用.NET 4数据可视化图表并使用Linq查询来获取图表的数据。我是Linq的新手,所以不确定如何说出这个查询。这是它的作用,我有以下表格从

中提取数据
  1. 订单
  2. ShipmentSchedule
  3. 订单表包含已订购的产品,OrderId,已发货的金额以及该订单的剩余数量。一个订单只能包含一个产品。我想在OrderShipment类中获得所有Ordershipments,制作一个List<>对于它并按每个产品分组,并显示订购的每个产品和已发货的总数量。下面的查询总结了所有订单的发货数量,这是正确的,但由于它正在制作OrderShipments列表,我想要所有货件中每个订单的剩余数量,并按产品加总。现在它将所有货物的剩余数量加起来是错误的,因为订单在所有货件中具有相同的剩余数量。如何获得每个产品的剩余数量,以便查询正确地按每个订单累计剩余数量?如果您有建议,请提供代码如何完成此操作的示例,您的帮助非常感谢,谢谢

     private class ChartDataPoint
        {
            public string ProductName { get; set; }
            public double QtyRemaining { get; set; }
            public double QtyShipped { get; set; }
        }
    
        private class OrderShipment
        {
            public string ProductName { get; set; }
            public double QuantityRemaining { get; set; }
            public double QuantityShipped { get; set; }
            public int OrderId { get; set; }
        }
    
    
          List<OrderShipment> productsOrdered =
              (from os in Statistics.OptimalShipments
               from o in Statistics.OrdersPlaced
               where ((os.Date >= Statistics.ShippingWindowStartDate) &&
                       (os.Date <= Statistics.ShippingWindowEndDate) &&
                       (os.OrderId == o.OrderId) &&
                      ((o.ClientLocationId == ClientLocation.ClientLocationId)))
               select new OrderShipment()
               {
                   ProductName = o.Product.Name,
                   QuantityRemaining = o.RemainingQuantity,
                   QuantityShipped = os.QuantityShipped,
    
               }).ToList();
    
            var query = productsOrdered.GroupBy(p => p.ProductName);
            List<ChartDataPoint> chartDataPoints = new List<ChartDataPoint>();
            foreach (var productGroup in query)
            {
                chartDataPoints.Add(new ChartDataPoint()
                {
                   ProductName = productGroup.Key,
    
                   // This is obv wrong this sums up the Remaining quantity across   
                   // all shipments for a order when we should be only taking the 
                   //Remaining quantity once for each order across all shipments.
                   QtyRemaining = productGroup.Sum(po => po.QuantityRemaining),
                   QtyShipped = productGroup.Sum(po => po.QuantityShipped)
                });
            }
    

1 个答案:

答案 0 :(得分:0)

据我了解,您的productGroup应该有很多按照产品名称分组的OrderShipment个对象。那么你想要总和QuantityShipped和QuantityRemaining应该都是相同的,你想只取这个值?

如果是这样,那么你应该这样做:

QtyRemaining = productGroup.First();

如果我误解了你可能想简化解释,可能还有一个例子......