我有以下串列:
var products = new List<(int ProductId, int Quantity)>
{
(10125237,2),
(7775711,1),
};
我將串列分組如下:
var groupedCustomerList = products
.GroupBy(u => u.ProductId)
.Select(grp => grp.AsEnumerable());
然后我將分組串列傳遞給以下方法:
public Builder Products(IEnumerable<(int ProductId, int Quantity)> products)
{
this.products.AddRange(products);
return this;
}
但是當我編譯時,我得到以下錯誤:
無法從 'System.Collections.Generic.IEnumerable<System.Collections.Generic.IEnumerable<(int VariantId, int Quantity)>>' 轉換為 'System.Collections.Generic.IEnumerable<(int variantId, int quantity)>'
自從我已經轉換groupedCustomerList為 后,我是否遺漏了什么IEnumerable?
uj5u.com熱心網友回復:
您可能需要按產品 ID 的總數量:
var groupedProductList = products
.GroupBy(u => u.ProductId)
.Select(g => (ProductId: g.Key, Quantity: g.Sum(p => p.Quantity)));
這是通過在 Select 子句中創建一個元組來實作的。產品 ID 是組的鍵(因為我們按此 ID 分組)。我們不是檢索組中產品的列舉,而是對這些產品的數量求和。
請注意,您的原始查詢會產生一個IEnumerable<IEnumerable<(int, int)>>,即嵌套列舉。
此解決方案回傳一個簡單的列舉:IEnumerable<(int ProductId, int Quantity)>與您的構建器方法兼容。
uj5u.com熱心網友回復:
U 可以直接將串列傳遞給函式,因為 List 已經繼承了 IEnumerable 介面。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/416943.html
標籤:
