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?
CodePudding user response:
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)>>, i.e., nested enumerations.
This solution returns a simple enumeration: IEnumerable<(int ProductId, int Quantity)> compatible with your builder method.
CodePudding user response:
U can directly pass the list to the function as List already inherits IEnumerable interface.
