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

时间:2016-08-31 22:51:44

标签: c# asp.net-mvc linq visual-studio-2015

在以下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)};

3 个答案:

答案 0 :(得分:0)

这不是非常有效,因为它为每个客户迭代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);

答案 1 :(得分:0)

您基本上需要在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属性的匿名对象的集合。

答案 2 :(得分:0)

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