The very flexible generic collection List<T> contains several methods that take a predicate as it's parameter. Coupled with Anonymous Methods this provides powerfully concise code for filtering, searching and sorting your collections.
List<Person> People = new List<Person>(); People.Add(new Person("Randy", "Patterson", 40));People.Add(new Person("John", "Smith", 15));People.Add(new Person("Caity", "Johnson", 13));People.Add(new Person("Jody", "Patterson", 39));People.Add(new Person("Chloe", "Dog", 30));People.Add(new Person("Corey", "Patterson", 18));
|
For Example, to filter the collection and display only my family members requires a single line of code
| IList<Person> family = People.FindAll(delegate(Person person) { return person.LastName == "Patterson"; }); |
And produces the following output
To remove the teenagers (not a bad proposition) also requires a single line
People.RemoveAll(delegate(Person person) { return person.Age > 12 && person.Age < 20; });
Sorting
Sorting requires a Comparison<T> delegate instead of Predicate<T> but operates in much the same fashion.
For example, sorting by last name requires this single line of code:
People.Sort(delegate(Person x, Person y) {return x.LastName.CompareTo(y.LastName) ;});
a slight modification will sort the list in descending order:
People.Sort(delegate(Person x, Person y) { return y.LastName.CompareTo(x.LastName); });
To sort by Last Name then First Name would look something like this:
People.Sort(delegate(Person x, Person y) { if (x.LastName == y.LastName) return x.FirstName.CompareTo(y.FirstName); else return x.LastName.CompareTo(y.LastName); }); |
Conclusion
I've just scratched the surface on what the generic List collection is capable of providing. There are several other generic methods that take delegates as parameters, such as ForEach and ConvertAll, that open up interesting possibilities in your code. Overall I find the Anonymous Method syntax a bit kludgy but C# 3.0 promises to reduce the syntactical noise and give us true (almost) Lambda Expressions.
