I have a foreach loop that cycles through each List from a master list List> and if a list contains an item, I want to remove it from the master list. My code works but even though the master list has fewer items, it still runs through each loop like it is reading from the original master list. I'm not sure how to properly remove items from the master list so that the loop behaves accordingly and only continues to execute for the remaining items in the correct master list.
public void GetBestCombo(List<List<SomeClass>> combosList)
{
foreach (var combo in combosList.ToList())
{
if (combo.ElementAt(0).ReturnAmount < 0)
{
combosList.RemoveAll(j => j.Contains(combo.ElementAt(0)));
}
}
}
This code works fine without any errors and my combosList goes from 16 items to 1 item but keeps on running through each iteration in the loop. I also remove everything and it still keeps running.
Here is some input and ouput information:
List> combosList contains 16 elements/lists
After RemoveAll code is run, combosList contains 1 element/list
Foreach loop keeps cycling through each item in the original combosList (16 items) when it should instead break the foreach loop