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

后端 未结 5 1403
走了就别回头了
走了就别回头了 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:24

    A predicate in T is a delegate that takes in a T and returns a bool. List.RemoveAll will remove all elements in a list where calling the predicate returns true. The easiest way to supply a simple predicate is usually a lambda expression, but you can also use anonymous methods or actual methods.

    {
        List vehicles;
        // Using a lambda
        vehicles.RemoveAll(vehicle => vehicle.EnquiryID == 123);
        // Using an equivalent anonymous method
        vehicles.RemoveAll(delegate(Vehicle vehicle)
        {
            return vehicle.EnquiryID == 123;
        });
        // Using an equivalent actual method
        vehicles.RemoveAll(VehiclePredicate);
    }
    
    private static bool VehiclePredicate(Vehicle vehicle)
    {
        return vehicle.EnquiryID == 123;
    }
    

提交回复
热议问题