I have a list of objects and I am trying to remove a specific object in the list by first checking a property in the object.
Originally I used a foreach
but then realised you can't use this while modifying a collection, so I decided to use a normal for
but then I'm not sure how to write code that does what I originally wrote.
How do I go about writing code to do what I originally had?
Thanks
Here's my code:
public void DeleteChunk(int ChunkID)
{
//foreach (Chunk i in ChunkList)
//{
// if (i.UniqueID == ChunkID)
// {
// ChunkList.Remove(i);
// }
//}
//This won't work because here i is just an integer so i.UniqueID won't exist.
for (int i = 0; i < ChunkList.Capacity; i++)
{
if (i.UniqueID == ChunkID)
{
ChunkList.Remove(i);
}
}
}
You can simplify this with linq:
var item = ChunkList.SingleOrDefault(x => x.UniqueId == ChunkID); if (item != null) ChunkList.Remove(item);
You can also do the following, which will also work if there is more than one match:
ChunkList.RemoveAll(x => x.UniqueId == ChunkID);
You're removing and then incrementing, which means you'll be one ahead of yourself. Instead, remove in reverse so you never mess up your next item.
for (int i = ChunkList.Count-1; i >=0; i--)
{
if (ChunkList[i].UniqueID == ChunkID)
{
ChunkList.RemoveAt(i);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With