Search code examples
c#listobjectremove-if

How to remove multiple objects in List by id?


I have a class as below

class MyClass
{
    public string id { get; set; }
    public string data { get; set; }
}

I have an array of ids I need to remove:

List<myClass> myObjArray = new List<myClass>;

myClass myObj1 = new myClass { id = "1", data = "aaa"};
myClass myObj2 = new myClass { id = "2", data = "bbb"};
myClass myObj3 = new myClass { id = "3", data = "ccc"};
myClass myObj4 = new myClass { id = "4", data = "ddd"};

myObjArray.Add(myObj1);
myObjArray.Add(myObj2);
myObjArray.Add(myObj3);
myObjArray.Add(myObj4);

string [] idToBeRemove = {"1", "3"};

Is there any method to remove the myObj in myObjArray where the id is in the idToBeRemove string?


Solution

  • List<T> has a method RemoveAll which will accomplish what you need. Unlike doing something like Where(...).ToList(), it will modify the existing list in place rather than create a new one.

    myObjArray.RemoveAll(item => idToBeRemove.Contains(item.id));
    

    Note that as your array of items to remove grows, you'll want to move to something more performant, such as a HashSet<T>, though with your current count of 2, it is not a pressing need.

    @Richardissimo also offers a good suggestion in the comments to your question for when the main list itself grows, a Dictionary<K, V> could be useful. Again, not an immediate need with a small list, but something to keep in mind as it grows and if performance is an issue.