Code:
List<Item> Contents = ObjectHandler.player.Contents.ToList<Item>() //Was HashTable
List<int> IDS = new List<int>(); //Holds Item IDs for later counting
foreach (Item I in Contents)
{
IDS.Add(I.ID); // Add ID to IDS
}
List<Item> newContents = Contents;
foreach (Item I in Contents)
{
if (IDS.Contains(I.ID)) //Check if the ID has already been used in Contents
{
newContents.Remove(I); //Remove it
}
}
Contents = newContents;
This Code snippet should prepare a list of IDs for later counting, and also remove duplicates from a list of Items. However, as soon as an item is present in Contents, however, I recieve an InvalidOperationException. I’m fairly certain I’m not modifying Contents, which the foreach is looping through, thus my confusion. Could somebody explain this to me? thanks.
You now have two variables pointing to the same collection.
You probably want to copy the collection by writing
new List<Item>(Contents).