Search code examples
c#linqunity-game-engine

How to sort List<> by object type using Linq?


I'm facing a problem while searching for duplicates in List<ShopItem>. The goal is to identify duplicates by checking the name of each object, and then when the output is a list<> of list<>s of duplicates, add a new CartItem to the cartitems list, that will later be returned.


public class ShopItemsSorter
{
    public IEnumerable<CartItemView> SortFromShopItemsToCartItemView(List<ShopItem>shopItemsToSort)
    {
        List<CartItem> cartItems = new List<CartItem>();
        var sortedShopItems = shopItemsToSort.GroupBy(item => item.Title).Where(item => item.Count() > 0);
        foreach (var shopItems in sortedShopItems)
        {
            CartItem cartItem = new CartItem(shopItems);
            cartItems.Add(cartItem);
        }
        return cartItems;
    }
}

public class CartItem
{
    public int Amount;
    public ShopItem ShopItem;

    public CartItem(List<ShopItem> shopitems)
    {
        if(shopitems.GroupBy(item => item.Title).Count() != 1)
            throw new Exception(nameof(shopitems));
        ShopItem = shopitems[0];
        Amount = shopitems.Count();
    }
}


However, I have an error saying: CS1503: Argument 1: cannot convert from 'System.Linq.IGrouping<string, ShopItem>' to 'System.Collections.Generic.List'


Solution

  • So the constructor of CartItem takes a List<ShopItem> but you don't pass it but a IGrouping<string, ShopItem> coming from here:

    var sortedShopItems = shopItemsToSort
        .GroupBy(item => item.Title)
        .Where(item => item.Count() > 1);
    

    You just need a ToList:

    foreach (var shopItems in sortedShopItems)
    {
        CartItem cartItem = new CartItem(shopItems.ToList());
        cartItems.Add(cartItem);
    }