Linq to SQL按聚合顺序排列

时间:2009-12-14 11:15:10

标签: linq-to-sql aggregate

我在LINQ to SQL中有一个非常简单的分组和聚合问题,这是我无法弄清楚的,这让我很生气。

我简化了这个例子:

类客户{    公共指导ID;    public String Name; }

班级订单{    public Guid Customer_Id;    公共双金额; }

如何按订单数量订购客户列表?以及他们购买的总金额?

3 个答案:

答案 0 :(得分:3)

return dataContext.Customers.OrderBy(cust => cust.Orders.Count)
    .ThenBy(cust => cust.Orders.Sum(order => order.Amount))
    .ToList();

答案 1 :(得分:1)

var qry1 = from c in db.Customers
           join o in db.Orders on c.Id equals o.Customer_Id into orders
           orderby orders.Count()
           select c;

var qry2 = from c in db.Customers
           join o in db.Orders on c.Id equals o.Customer_Id into orders
           orderby orders.Sum(o => o.Amount)
           select c;

答案 2 :(得分:0)

按订单数量:

var customers = (from c in db.Customers
                 select new 
                  {
                    c.Name, 
                    OrderCount = c.Orders.Count()
                  }).OrderBy(x => x. OrderCount);

购买总金额:

var customers = (from c in db.Customers
                 select new 
                  {
                    c.Name, 
                    Amount = (from order in c.Orders
                              select order.Amount).Sum()
                  }).OrderBy(x => x.Amount);