组列表并转换为 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
?
你可以直接将列表传递给函数,因为List已经继承了IEnumerable接口
您可能需要产品编号的总数量:
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)>>
,即嵌套枚举。
此解决方案returns 一个简单的枚举:IEnumerable<(int ProductId, int Quantity)>
与您的构建器方法兼容。
我有以下列表:
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
?
你可以直接将列表传递给函数,因为List已经继承了IEnumerable接口
您可能需要产品编号的总数量:
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)>>
,即嵌套枚举。
此解决方案returns 一个简单的枚举:IEnumerable<(int ProductId, int Quantity)>
与您的构建器方法兼容。