Generic FindAll method
In our current project I came up with a situation where in needed to filter some values in a generic List. So I used generic’s FindAll method. Its very powerful way to find elements that we want in a generic collection. and it’s use a Predicate to do all the filtering part . Here is an example of to use the FindAll method. I think is will be useful to the people who work with generic collections . using this you don’t need to use a foreach loop
Ex:-
Let’s assume we have a generic list of USER Object, and USER object has properties call FullName (string), Age(int) And isActive(bool) . So let’s think we get list (LIST<t>
of user objects from a method call GetAllUsers, so our code will be like
List<User> ListUsers = GetAllUsers();
Ok now we want List of users that are only active. So to this where we can use the FindAll method
List< User > ListActiveUSers = ListUsers.FindAll(ActiveUsersOnly);
Predicate<User> ActiveUsersOnly = delegate(User user)
{
return user.isActive == true;
};
Here we call the FindAll method for the ListUsers’s List, it take a Predicate as the parameter. So in the Predicate deligate what we have to do is create a user object and check of the condition we want pass. So here it will check with each element of our old list and the elements that match will save in a return list.
This is a real performance booster and time saver




Leave a Reply