How to Remove multiple items in List using RemoveAll on condition?

前端 未结 4 1459
清酒与你
清酒与你 2021-01-05 12:01

I tried like following.

MyList.RemoveAll(t => t.Name == \"ABS\");
MyList.RemoveAll(t => t.Name == \"XYZ\");
MyList.RemoveAll(t => t.Name == \"APO\")         


        
相关标签:
4条回答
  • 2021-01-05 12:41

    You only need one lambda expression - the || goes within that:

    MyList.RemoveAll(t => t.Name == "ABS" || t.Name == "XYZ" || t.Name == "APO");
    

    In other words, "Given a t, I want to remove the element if t.Name is ABS, or if t.Name is XYZ, or if t.Name is APO."

    There's only one "given a t" in there, which is what the t => part means, effectively.

    0 讨论(0)
  • 2021-01-05 12:42

    A more extnsible approach would be to have a List for what to remove then

    List<T> toRemove = ...
    MyList.RemoveAll(t =>  toRemove.Contains(t.Name));
    

    where T is a string in your example

    0 讨论(0)
  • 2021-01-05 12:49

    or

    var nameToRemove = new[]{"ABS", "XYZ", "APO"};
    MyList.RemoveAll(t => nameToRemove.Contains(t.Name))
    
    0 讨论(0)
  • 2021-01-05 12:55

    If it's not required at any time that there are multiple items in the list, you should consider using a HashSet instead of List

    0 讨论(0)
提交回复
热议问题