带有LINQ的金额列的总和(两个表)

问题描述 投票:0回答:2

我有两个表,简单地说:

产品:ProductID,产品名称

订单:订单ID,产品ID,数量,状态

我想用C#编写LINQ查询,选择ProductName,Sum(Amount),其中Status = 1

我被这个简单的查询所困扰:(

c# c#-4.0 linq-to-entities group-by
2个回答
2
投票
class Program
{
  class Product
  {
     public int ProductID { get; set; }
     public string ProductName {get; set; }
     public Product(int ProductID, string ProductName)
     {
        this.ProductID = ProductID;
        this.ProductName = ProductName;
     }
  }

  class Order
  {
     public int OrderID { get; set; }
     public int ProductID { get; set; }
     public decimal Amount { get; set; }
     public int Status { get; set; }
     public Order(int OrderID, Product product, decimal Amount, int Status)
     {
        this.OrderID = OrderID;
        this.ProductID = product.ProductID;
        this.Amount = Amount;
        this.Status = Status;
     }
  }

  private static Product[] Products;

  private static Order[] Orders;

  static void Main(string[] args)
  {
     Products = new Product[]
     {
        new Product(1, "Bolt"),
        new Product(2, "Nut"),
        new Product(3, "Mounting Plate A"),
        new Product(4, "Mounting Plate B")
     }; 

     Orders = new Order[]
     {
        new Order(1, Products[0], 1.12M, 0),
        new Order(2, Products[1], 0.66M, 1),
        new Order(3, Products[2], 4.12M, 0),
        new Order(4, Products[0], 1.11M, 1),
        new Order(5, Products[1], 0.67M, 1)
     };

     var results = from p in Products
                   join o in Orders on p.ProductID equals o.ProductID
                   where o.Status == 1
                   group o by p
                      into orderTotals
                      select new {ProductName = orderTotals.Key.ProductName, TotalAmount = orderTotals.Sum(o => o.Amount)};

     foreach(var result in results)
     {
        Console.WriteLine("{0}: {1}", result.ProductName, result.TotalAmount);
     }
  }
}

1
投票

虽然不是最佳选择,但这应该可以工作:

© www.soinside.com 2019 - 2024. All rights reserved.