开发者

Linq to SQL order by aggregate

开发者 https://www.devze.com 2022-12-14 10:47 出处:网络
I have a very simple grouping and aggregation problem in LINQ to SQL that I just 开发者_如何转开发can\'t figure out, and it is driving me mad.

I have a very simple grouping and aggregation problem in LINQ to SQL that I just 开发者_如何转开发can't figure out, and it is driving me mad.

I've simplified things into this example:

class Customer { public Guid Id; public String Name; }

class Order { public Guid Customer_Id; public double Amount; }

How do I get a list of customers ordered by the number of orders they have? And on the total amount they have purchased for?


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


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;


By number of orders:

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

By total amount purchased:

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);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号