I have two classes ShoppingCart and CartItems like this:
public class ShoppingCart
{
public Guid Id { get; set; }
public DateTime CreatedOn { get; set; }
public Guid OwnerId { get; set; }
public ICollection<CartItem> Items { get; set; }
}
public class CartItem
{
public Guid Id { get; set; }}
public int Quantity { get; set; }
public Guid ProductId { get; set; }
public Guid ShoppingCartId { get; set; }
}
I want get all CartItems by ownerId using this method:
public IEnumerable<CartItem> GetCartItems(Guid ownerId)
{
return _shoppingCarts.Where(row => row.OwnerId == ownerId)
.Select(row => row.Items)
.ToList() ;
}
but it returns an error :
Cannot implicitly convert type System.Collections.Generic.List<System.Collections.Generic.ICollection<CartItem>>'to System.Collections.Generic.IEnumerable<CartItem>
The current return value of your method is of type IEnumerable<List<CartItem>>.
Instead of Select you should use SelectMany, like this:
public IEnumerable<CartItem> GetCartItems(Guid ownerId)
{
return _shoppingCarts.Where(row => row.OwnerId == ownerId).SelectMany(row => row.Items).ToList() ;
}
SelectMany flattens the collection of collections of CartItem to one collection of CartItem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With