如何对此进行LINQ查询

本文关键字:LINQ 查询 | 更新日期: 2023-09-27 18:02:08

好了,困了一天了,谁来帮帮我吧!

我想选择特定客户拥有的每种可能商品的数量,而不管他们是否订购了该商品。因此,如果他们没有订购它(即它不在订单表中),则返回数量的值为0。

订单 CustomerId ItemId Quantity

项目

ItemId ItemName

CustomerId CustomerName

我猜这将涉及某种子查询,但真的不确定。

from c in customers
join o in Orders
on c.CustomerId == o.CustomerId
select c.CustomerName, o.Quantity
where c.CustomerId == customerId

如何对此进行LINQ查询

这引起了我的兴趣,所以我写了一个控制台应用程序来做这件事。

Andomar在我之前回答了几分钟(+1)。这是我的独立解决方案,但非常接近他的,并不简单…

class Program {
    private class CustomerDto {
        public int CustomerId { get; set; }
        public string CustomerName { get; set; }
    }
    private class ItemDto {
        public int ItemId { get; set; }
        public string ItemName { get; set; }
    }
    private class OrderDto {
        public int Id { get; set; }
        public int ItemId { get; set; }
        public int CustomerId { get; set; }
        public int Quantity { get; set; }
    }
    private class CustomerOrderDto {
        public int CustomerId { get; set; }
        public int ItemId { get; set; }
        public int TotalQuantity { get; set; }
    }
    static void Main(string[] args) {
        List<CustomerDto> Customers = new List<CustomerDto>() { 
            new CustomerDto() { CustomerId = 1, CustomerName = "one"},
            new CustomerDto() { CustomerId = 2, CustomerName = "two"},
            new CustomerDto() { CustomerId = 3, CustomerName = "three"}
        };
        List<ItemDto> Items = new List<ItemDto>() { 
            new ItemDto() { ItemId = 1, ItemName = "item one"},
            new ItemDto() { ItemId = 2, ItemName = "item two"},
            new ItemDto() { ItemId = 3, ItemName = "item three"}
        };
        // customer1 has 2 orders for item 1, 0 for item 2 or 3
        // customer2 has 1 order for item 2, 0 for item 1 or 3
        // customer3 has 1 order for item 2, 1 order for item 3 and 0 for item 1
        List<OrderDto> Orders = new List<OrderDto>() { 
            new OrderDto() { Id = 1, CustomerId = 1, ItemId = 1, Quantity = 3 },
            new OrderDto() { Id = 1, CustomerId = 1, ItemId = 1, Quantity = 5 },
            new OrderDto() { Id = 1, CustomerId = 3, ItemId = 2, Quantity = 5 },
            new OrderDto() { Id = 1, CustomerId = 3, ItemId = 3, Quantity = 5 },
            new OrderDto() { Id = 1, CustomerId = 2, ItemId = 2, Quantity = 5 }
        };
        List<CustomerOrderDto> results = (from c in Customers
                                          from i in Items
                                          join o in Orders on
                                            new { c.CustomerId, i.ItemId } equals
                                            new { o.CustomerId, o.ItemId } into oj
                                          from o in oj.DefaultIfEmpty()
                                          let x = o ?? new OrderDto() { CustomerId = c.CustomerId, ItemId = i.ItemId, Quantity = 0 }
                                          group x by new { x.CustomerId, x.ItemId } into g
                                          select new CustomerOrderDto() {
                                              CustomerId = g.Key.CustomerId,
                                              ItemId = g.Key.ItemId,
                                              TotalQuantity = g.Select(x => x.Quantity).Sum()
                                          }
                                          ).ToList();
        foreach (var result in results) {
            Console.WriteLine("Customer {0} purchased {1} units of item {2}",
                result.CustomerId, result.TotalQuantity, result.ItemId);
        }
        Console.ReadKey(true);
    }
}

在SQL中,这很简单:

select  c.name
,       i.name
,       isnull(sum(o.quantity),0)
from    customers c
cross join
        items i
left join
        orders o
on      o.customerid = c.customerid
        and o.itemid = o.itemid
group by
        c.name
,       i.name        

翻译成LINQ,这就变成:

from c in Customers
from i in Items 
join o in Orders 
    on new { c.Customerid, i.Itemid } 
    equals new { o.Customerid, o.Itemid } 
    into o1
from o2 in o1.DefaultIfEmpty()
group o2.Quantity
    by new { CustomerName = c.Name, ItemName = i.Name }
    into q
select new { 
    q.Key.CustomerName, 
    q.Key.ItemName, 
    Quantity = q.Sum() ?? 0 
}

我希望其他人发布一个更简单的LINQ版本,因为这看起来太复杂了:)

LINQ表达式

from c in Customers
from i in Items
select ...

是所有客户和项目的交叉连接。所以剩下唯一要做的就是把每一个的数量加起来:

var result = from c in Customers
             from i in Items
             select new
             {
                 Customer = c,
                 Item = i,
                 Quantity = (from o in Orders
                             where o.CustomerId == c.CustomerId && o.ItemId == i.ItemId
                             select o.Quantity).Sum(),
             };

注意,对于空的IEnumerable<int>(即没有找到顺序),Sum返回0。

Linq

from t in Customers
join t2 in Orders on t.CustomerId equals (int)t2.CustomerId into t2Join
from t2 in t2Join.DefaultIfEmpty()
group t by t into t_g
select new 
      { 
       CustomerId = t_g.Key.CustomerId, 
       OrdersId = t_g.Key.OrdersId,
       Quantity = t_g.Key.Orders.Where(c => c.CustomerId == t_g.Key.CustomerId)
                                .Sum(c => c.Quantity) 
      };