Home > database >  C# - Match between items in List<Items> to ItemsContainer in List<ItemsContainer>
C# - Match between items in List<Items> to ItemsContainer in List<ItemsContainer>

Time:01-12

I have a List of Items and a List of ItemsContainer which is a class that holds items.

  1. all the items are unique
  2. every item is located in at most one ItemContainer
  3. the ItemContainer support only: Remove(Item) and Contains(Item) methods

I would like to remove all the items in my list from all the itemContainers.

right now I'm thinking of doing something like that:

    List<ItemContainer> itemContainerList = ...
    List<Item> itemsList = ...

          
foreach (ItemContainer itemContainer in itemContainerList)
            {
                foreach (Item item in itemsList)
                {
                    if (itemContainer.Contains(item))
                    {
                        itemContainer.Remove(item);
                    }
                }
            }

Hoping to make this more efficient and elegant.

Thanks, Aviram.

CodePudding user response:

Following on from further information being unveiled, I've found that the constraints mean that any of the "conventionally efficient" ways of doing it aren't applicable.

Based on your constraints, I can only suggest flipping the loops:

foreach (Item item in itemsList)
{
    foreach (ItemContainer itemContainer in itemContainerList)
    {
        if (itemContainer.Contains(item))
        {
            itemContainer.Remove(item);
            break;
        }
    }
}

It's still not ideal, due to the unfortunate prior existing issues of your set-up, but it'll be slightly quicker by virtue of only going through the items once.

CodePudding user response:

You can use .RemoveAll() with .Any(),

var removedItemCount = itemContainerList
           .RemoveAll(itemContainer => itemsList
           .Any(item => itemContainer.Contains(item)));
  •  Tags:  
  • Related