Ken Getz wrote a good article titled Predicates and Actions about the advantage of the new generic features in .NET 2.0 Framework. One issue I ran into using predicates was passing an argument to use as the filter. For example, in the callback method Match() below, the predicate searches the states generic list for those that start with “C”, but the string to search for is hardcoded because the predicate signature only allows for one argument that is of the same type as the items in the generic list.
Using a Lambda Expression removes the need for a callback method (anonymous methods as well), so the filter is inline or it could be encapsulated in the method that takes the filter as an argument.
The following code snippet lists 3 different ways to find an item in a generic list.
static void Main( string[] args ) { // Create an abbreviated subset of states List<string> states = new List<string> { "AL", "AZ", "CA", "CO", "MA", "MD", "NJ", "NV", "TX", "TN" }; //---------------------------------------------------------- // You do not need to create the delegate explicitly // http://msdn.microsoft.com/en-us/library/bfcke1bz.aspx //---------------------------------------------------------- // // Using an concrete method that matches the predicate // signature to find the matching states List<string> methoddel = states.FindAll( Match ); // Using an Anonymous Method to find the matching states List<string> anonymous = states.FindAll( delegate( string s ) { return s.StartsWith( "C" ); } ); // Using a Lambda Expression to find the matching states //(new w/ C# 3.0) List<string> lambdaexp = states.FindAll( s => s.StartsWith( "C" ) ); // Display the output from lambdaexp lambdaexp.ForEach( Print ); Console.ReadLine(); } // Finds the matching states static bool Match( string s ) { return s.StartsWith( "C" ); } // Display the contents static void Print( string s ) { Console.WriteLine( s ); }








