Thursday, March 20, 2008

Using Anonymous method Predicates to filter data in Generic List

Predicate is a delegate to a method that returns true if the object passed to it passes the condition defined in the delegate.

The List.FindAll() method finds all objects that match the supplied criteria specified in a predicate and returns a List. If no items are found, the resulting collection will be empty. The normal way of using predicates to filter a List collection uses a hard coded criterion for matching strings. The example illustrated in MSDN uses this approach. It uses a predicate which has a static method implementation with a hardcoded search string for matching the values. But in real world scenario we cannot use hardcoded strings for searching a List collection, instead we need a parameterized approach.

Using anonymous methods as an implementation of the System.Predicate can help me to achieve this without using a Static method as predicate for the List.FindAll() method. Using Anonymous methods it is possible to pass the complete method as parameter.
In the example given below I have followed this approach to search the occurrence of a string in a List collection.

List _users = new List();
_users.Add(new User("John Micheal", 23, "Bahamas"));
_users.Add(new User("Steve Hickman", 34, "Kensas"));
_users.Add(new User("Micheal Norman", 24, "New York"));
_users.Add(new User("John Ruf", 45, "New Jersey"));
_users.Add(new User("Alisha Menon", 34, "Bangalore"));
_users.Add(new User("John A", 56, "New York"));
_users.Add(new User("Amir Sinha", 34, "Bangalore"));

List _nameFilteredUsers = _users.FindAll(
delegate(User _user)
{
return _user.Name.Contains("John");
});

The _nameFilteredUsers returned the following List of users

John Micheal 23 Bahamas
John Ruf 45 New Jersey
John A 56 New York


Similarly we can use the same approach to filter users based on age as

List _ageFilteredUsers = _users.FindAll(
delegate(User _user)
{
return _user.Age > 30;
});


You can also create a method that filters the List of users and returns the filtered list based on the parameter passed.

private List FilterUserByName(List _users, String _searchString)
{
return _users.FindAll(delegate(User _user)
{
return _user.Name.Contains(_searchString);
});
}


And call the method like
List _filteredUsers = FilterUserByName(_users, "John");

No comments: