Linq to SQL 按聚合排序

发布于 2024-08-14 20:33:58 字数 207 浏览 4 评论 0原文

我在 LINQ to SQL 中遇到一个非常简单的分组和聚合问题,但我无法弄清楚,这让我抓狂。

我将事情简化为这个例子:

class Customer { 公共引导 ID; 公共字符串名称; }

类订单 { 公共指导客户 ID; 公共双倍金额; ?

如何获取按订单数量排序的客户列表 他们购买的总金额是多少?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

甜警司 2024-08-21 20:33:58
return dataContext.Customers.OrderBy(cust => cust.Orders.Count)
    .ThenBy(cust => cust.Orders.Sum(order => order.Amount))
    .ToList();
return dataContext.Customers.OrderBy(cust => cust.Orders.Count)
    .ThenBy(cust => cust.Orders.Sum(order => order.Amount))
    .ToList();
以可爱出名 2024-08-21 20:33:58
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;
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;
白衬杉格子梦 2024-08-21 20:33:58

按订单数量:

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

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文