LINQ查询-显示有订单数量的客户,包括没有订单的客户

本文关键字:客户 包括没 查询 LINQ 单数量 显示 | 更新日期: 2023-09-27 18:05:07

在以下LINQ查询中,我需要显示All客户及其下订单总数,包括尚未下任何订单的客户:

型号

Public class Customer
{
   public int CustomerId { get; set; }
   public string Name{ get; set; }
}
Public class Order
{
   public int OrderId { get; set; }
   public int CustomerId { get; set; }
}

LINQ查询:问题:如何显示ALL客户(包括没有订单的客户(和每个客户的订单总数(对于客户ID不在订单表中的客户为零(

var Query1 = from c in Customers
             join o in Orders into co
             from t in co.DefaultIfEmpty()
             select new {CustomerID = c.CustomerId, OrderID = (t == null ? 0 : t.OrderId)};

LINQ查询-显示有订单数量的客户,包括没有订单的客户

您基本上需要在Customer表和Customer Order表之间执行LEFT JOIN,然后根据该结果进行分组,以计算每个客户的订单。

假设你有一个像这样的类

public class CustomerOrder
{
  public int CustomerId { set; get; }
  public int? OrderId { set; get; }
}

此类用于存储左联接结果的每个项目

现在,您需要首先执行LEFT JOIN,并将其结果投影到CustomerOrder类对象的列表中,然后在上执行GroupBy

var usersWithCount = (from c in db.Customers
    join o in db.Orders on c.CustomerId equals o.CustomerId 
    into result
    from sub in result.DefaultIfEmpty()
         select new CustomerOrder{  OrderId= sub!=null ? sub.OrderId :(int?) null,
                                    CustomerId = u.CustomerId }
) // Here we have the left join result.
.GroupBy(g => g.CustomerId , (k, orders) => new { 
                    CustomerId = k, 
                    OrderCount = orders.Count(t=>t.OrderId !=null)}).ToList();

存储在usersWithCount中的结果将是具有CustomerIdOrderCount属性的命名对象的集合。

这不是很有效,因为它为每个客户迭代Orders,但它会完成任务:

var query = Customers
    .Select(c => new
        {
            Name = c.Name,
            NumOrders = Orders.Count(o => o.CustomerId = c.CustomerId)
        });
foreach (var result in query)
    Console.WriteLine("{0} -> {1}", result.Name, result.NumOrders);
var Query1 = from c in Customers
     join o in Orders on c.CustomerId equals o.CustomerId into OrdersGroup
    from item in OrdersGroup.DefaultIfEmpty(new Order { OrderId = 0, CustomerId = 0 })                      
    select new {CustomerID = c.CustomerId, OrderID = (item == null ? 0 : item.OrderId)};

这将返回所有客户(即使他们没有订单(和订单

https://dotnetfiddle.net/BoHx2d