Predicate Delegate with Example in C# with List<T>.Find
The below codesnippet will show how to use Predicate delegate with a generic list(List<T>).
See the comments in code to know more about the code.
static string test = "";
public static void Main() { // Create an List of five strings. List empList = new List(); empList.Add("Sam"); empList.Add("Bob"); empList.Add("Steve"); empList.Add("Mark"); empList.Add("Frank");
// Create a global variable to be used by the delegate function. // This would not be necessary if you want to hard code test // condition in function. test = "Mark"; string first = empList.Find(new Predicate(SearchList));
// Note that you ca n use an Anonymous call to define the condition. test = "Steve"; string next = empList.Find(delegate(string t) { if (t.CompareTo(test) == 0) return true; return false; });
// Display the first structure found. Console.WriteLine(first); Console.WriteLine(next); } // This method implements the test condition for the Find method. private static bool SearchList(string t) { if (t.CompareTo(test) == 0) { return true; } return false; } }
|