List<object>.RemoveAll - How to create an appropriate Predicate

后端 未结 5 1369
走了就别回头了
走了就别回头了 2020-12-28 13:20

This is a bit of noob question - I\'m still fairly new to C# and generics and completely new to predicates, delegates and lambda expressions...

I have a class \'Enqu

5条回答
  •  独厮守ぢ
    2020-12-28 13:47

    The RemoveAll() methods accept a Predicate delegate (until here nothing new). A predicate points to a method that simply returns true or false. Of course, the RemoveAll will remove from the collection all the T instances that return True with the predicate applied.

    C# 3.0 lets the developer use several methods to pass a predicate to the RemoveAll method (and not only this one…). You can use:

    Lambda expressions

    vehicles.RemoveAll(vehicle => vehicle.EnquiryID == 123);
    

    Anonymous methods

    vehicles.RemoveAll(delegate(Vehicle v) {
      return v.EnquiryID == 123;
    });
    

    Normal methods

    vehicles.RemoveAll(VehicleCustomPredicate);
    private static bool
    VehicleCustomPredicate (Vehicle v) {
        return v.EnquiryID == 123; 
    }
    

提交回复
热议问题