3

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?

4

4 回答 4

9

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.

于 2018-11-28T06:34:51.137 回答
3

To remove from existing List you can use List.RemoveAll(Predicate):

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

To get result in new collection you can use Enumerable.Where and Enumerable.Contains:

var result = myObjArray.Where(m => !idToBeRemove.Contains(m.id)).ToList();
于 2018-11-28T06:29:21.097 回答
0
  var result = myObjArray.Where(m => !idToBeRemove.Contains(m.id)).ToList();
            foreach (var item in result)
            {
                myObjArray.Remove(item);
            }
于 2018-11-28T06:31:13.680 回答
0

Use this to remove id:

myObjArray.RemoveAll(item => idToBeRemove.Contains(item.id));
于 2018-11-28T06:41:31.070 回答