簡體   English   中英

分組列表並轉換為 IEnumerable

[英]Group List and Convert to IEnumerable

我有以下列表:

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;
}

但是當我編譯時,我得到以下錯誤:

cannot convert from 'System.Collections.Generic.IEnumerable<System.Collections.Generic.IEnumerable<(int VariantId, int Quantity)>>' to 'System.Collections.Generic.IEnumerable<(int variantId, int quantity)>'

自從我已經將groupedCustomerList轉換為IEnumerable后,我是否遺漏了什么?

您可能需要按產品 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)>與您的構建器方法兼容。

U 可以直接將列表傳遞給 function,因為 List 已經繼承了 IEnumerable 接口。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM