Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return nested List in Entity Framework

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>
like image 726
temp125050 Avatar asked Oct 29 '25 20:10

temp125050


1 Answers

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.

like image 70
Domysee Avatar answered Oct 31 '25 11:10

Domysee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!