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)>'
Am I missing something since I have already converted groupedCustomerList
to an IEnumerable
?
You probably want the total quantity by product 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. The product Id is the key of the group (since we grouped by this 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.
This solution returns a simple enumeration: IEnumerable<(int ProductId, int Quantity)>
compatible with your builder method.
U can directly pass the list to the function as List already inherits IEnumerable interface.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.