如何将数组拆分为多个具有相同linq的数组

本文关键字:数组 linq 拆分 | 更新日期: 2023-09-27 18:08:15

我有一个数组:

OrderProduct[] OrderProductsOrder = new OrderProduct[] { 
new OrderProduct { OrderID = 1, ProductID = 2, OrderCustomerID = 1 }, 
new OrderProduct { OrderID = 2, ProductID = 1, OrderCustomerID = 1 }, 
new OrderProduct { OrderID = 1, ProductID = 3, OrderCustomerID = 1 }, 
new OrderProduct { OrderID = 2, ProductID = 1, OrderCustomerID = 2 }, 
new OrderProduct { OrderID = 1, ProductID = 2, OrderCustomerID = 3 }, 
new OrderProduct { OrderID = 2, ProductID = 1, OrderCustomerID = 3 }};

如何将该数组拆分为三个数组,按CustomerID排序,使用linq。结果应该是这三个数组:

OrderProduct[] Customer1Order = new OrderProduct[] { 
new OrderProduct { OrderID = 1, ProductID = 2, OrderCustomerID = 1 }, 
new OrderProduct { OrderID = 2, ProductID = 1, OrderCustomerID = 1 }, 
new OrderProduct { OrderID = 1, ProductID = 3, OrderCustomerID = 1 }};
OrderProduct[] Customer2Order = new OrderProduct[] 
{new OrderProduct { OrderID = 2, ProductID = 1, OrderCustomerID = 2 }};
OrderProduct[] Customer3Order = new OrderProduct[] {  
new OrderProduct { OrderID = 1, ProductID = 2, OrderCustomerID = 3 }, 
new OrderProduct { OrderID = 2, ProductID = 1, OrderCustomerID = 3 }};

如何将数组拆分为多个具有相同linq的数组

编辑,删除GroupBy()建议,因为它是多余的(由Innat3提供)

完全没有理由使用GroupBy(),只使用Where

OrderProduct[] Customer1Order = OrderProductsOrder.Where(o => o.OrderCustomerID == 1).ToArray();
OrderProduct[] Customer2Order = OrderProductsOrder.Where(o => o.OrderCustomerID == 2).ToArray();
OrderProduct[] Customer3Order = OrderProductsOrder.Where(o => o.OrderCustomerID == 3).ToArray();

首先按OrderCustomerID对条目进行分组,并从每组中构造一个数组。之后,将组添加到字典中:

var byCustId = OrderProductsOrder
    .GroupBy(p => p.OrderCustomerID)
    .ToDictionary(g => g.Key, g => g.ToArray());

现在您可以使用TryGetValueoperator []抓取单个数组:

OrderProduct[] customer2Order;
if (byCustId.TryGetValue(2, out customer2Order) {
    ... // Use customer2Order array
}