[英]Group List and Convert to IEnumerable
I have the following List:我有以下列表:
var products = new List<(int ProductId, int Quantity)>
{
(10125237,2),
(7775711,1),
};
And I am grouping the list as follows:我将列表分组如下:
var groupedCustomerList = products
.GroupBy(u => u.ProductId)
.Select(grp => grp.AsEnumerable());
I then pass the grouped list to the following Method:然后我将分组列表传递给以下方法:
public Builder Products(IEnumerable<(int ProductId, int Quantity)> products)
{
this.products.AddRange(products);
return this;
}
But when I compile, I get the following error:但是当我编译时,我得到以下错误:
cannot convert from 'System.Collections.Generic.IEnumerable<System.Collections.Generic.IEnumerable<(int VariantId, int Quantity)>>' to 'System.Collections.Generic.IEnumerable<(int variantId, int quantity)>'
cannot convert from 'System.Collections.Generic.IEnumerable<System.Collections.Generic.IEnumerable<(int VariantId, int Quantity)>>' to 'System.Collections.Generic.IEnumerable<(int variantId, int quantity)>'
Am I missing something since I have already converted groupedCustomerList
to an IEnumerable
?自从我已经将
groupedCustomerList
转换为IEnumerable
后,我是否遗漏了什么?
You probably want the total quantity by product Id:您可能需要按产品 ID 的总数量:
var groupedProductList = products
.GroupBy(u => u.ProductId)
.Select(g => (ProductId: g.Key, Quantity: g.Sum(p => p.Quantity)));
This is achieved by creating a tuple in the Select-clause.这是通过在 Select 子句中创建一个元组来实现的。 The product Id is the key of the group (since we grouped by this Id).
产品 ID 是组的键(因为我们按此 ID 分组)。 Instead of retrieving a enumeration of products in the group, we sum the quantities of these products.
我们不是检索组中产品的枚举,而是对这些产品的数量求和。
Note that your original query yields a IEnumerable<IEnumerable<(int, int)>>
, ie, nested enumerations.请注意,您的原始查询会产生
IEnumerable<IEnumerable<(int, int)>>
,即嵌套枚举。
This solution returns a simple enumeration: IEnumerable<(int ProductId, int Quantity)>
compatible with your builder method.此解决方案返回一个简单的枚举:
IEnumerable<(int ProductId, int Quantity)>
与您的构建器方法兼容。
U can directly pass the list to the function as List already inherits IEnumerable interface. U 可以直接将列表传递给 function,因为 List 已经继承了 IEnumerable 接口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.