Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Remove object from list of objects

Tags:

c#

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);
            }
        }

    }
like image 300
user9993 Avatar asked Sep 20 '13 13:09

user9993


2 Answers

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); 
like image 142
Khan Avatar answered Sep 23 '22 21:09

Khan


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);
    }
}
like image 24
bland Avatar answered Sep 26 '22 21:09

bland