假設我有一個串列ProductId:
12345
23456
34567
以及各個倉庫中每種產品的可用數量串列,按 ID:
Dictionary<ProductId,Dictionary<WarehouseId,quantity>>
我如何檢查哪些倉庫有清單中所有產品的庫存(每個數量 >= 1)?是否可以使用 LINQ 來實作?
uj5u.com熱心網友回復:
- 加入
productIds串列
.Join(productIds,
x => x.Key,
y => y,
(x, y) => x)
或檢查productDict包含鍵入productIds
.Where(x => productIds.Contains(x.Key)
- 轉換為倉庫清單。
- 展平倉庫清單。
.GroupBy倉庫編號。- 使用 轉換分組的倉庫資料
IsAllProductsAvailable。 - 使用 查詢倉庫
IsAllProductsAvailable = true。
var result = productDict
.Join(productIds,
x => x.Key,
y => y,
(x, y) => x)
.Select(x => new
{
Warehouses = x.Value
.Select(y => new
{
ProductId = x.Key,
WarehouseId = y.Key,
Quantity = y.Value
})
.ToList()
})
.SelectMany(x => x.Warehouses)
.GroupBy(x => x.WarehouseId)
.Select(g => new
{
WarehouseId = g.Key,
IsAllProductsAvailable = g.All(x => x.Quantity >= 1),
Products = g.ToList()
})
.Where(x => x.IsAllProductsAvailable)
.ToList();
示例程式
輸出
[{
"WarehouseId": 3,
"IsAllProductsAvailable": true,
"Products": [
{"ProductId":12345,"WarehouseId":3,"Quantity":1},
{"ProductId":23456,"WarehouseId":3,"Quantity":50},
{"ProductId":34567,"WarehouseId":3,"Quantity":20}
]
}]
uj5u.com熱心網友回復:
假設您有以下欄位:
List<int> productIds;
Dictionary<int, Dictionary<int, int>> quantityByWarehouseByProductId;
然后你可以:
- 相交
quantityByWarehouseByProductId(通過字典鍵)與productIds, 僅保留相關條目quantityByWarehouseByProductId - 通過與每個相關產品 ID 關聯的倉庫 ID內部字典條目選擇所有數量,并展平這些數量的集合,使用
SelectMany() - 按倉庫 ID(即內部字典鍵)對結果進行分組
- 僅按倉庫 ID條目保留所有所需產品的庫存數量
- 選擇倉庫編號
如下:
IEnumerable<int> warehouseIdsWithAllProductsInStock = quantityByWarehouseByProductId
.IntersectBy(productIds, qbwForPid => qbwForPid.Key)
.SelectMany(qbwForPid => qbwForPid.Value)
.GroupBy(qbw => qbw.Key)
.Where(qsbw => qsbw.All(qbw => qbw.Value >= 1))
.Select(qsbw => qsbw.Key);
為了使名稱保持簡短,我在示例中使用了以下縮寫:
qbwForPid: 產品編號的倉庫數量qbw: 倉庫數量qsbw: 倉庫數量
注意:此方法假定所有現有倉庫 ID 都存在于 KeyValuePair內部字典的 a 中。
示例小提琴在這里。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/444626.html
上一篇:如何在LINQ中過濾先進后出記錄
下一篇:按ID排序,然后按年齡排序
