static List <int> MyFindAll(MyPredicate2 mp2) { int numToFind = 20; List <int> list = new List <int>(); foreach (int x in array) { if (mp2(numToFind, x)) { list.Add(x); } } return(list); }
static void Main(string[] args) { PreloadArray(); Display(array); // find the first value that is positive MyPredicate predicate = IsPositive; int firstPosX = Find(predicate); // compiler creates a delegate to be passed to the Find() method Console.WriteLine($"\n\nFirst positive value: { firstPosX }."); // find the first value that is negative predicate = IsNegative; int firstNegX = Find(predicate); Console.WriteLine($"\n\nFirst negative value: { firstNegX }."); // find the first value that is negative and odd predicate = IsNegativeOdd; int firstNegOddX = Find(predicate); Console.WriteLine($"\n\nFirst negative odd value: { firstNegOddX }."); // find the first value that is positive and even predicate = IsPositiveEven; int firstPosEvenX = Find(predicate); Console.WriteLine($"\n\nFirst positive even value: { firstPosEvenX }."); // another way to do this: pass a delegate referencing a lambda expression MyPredicate predicate2 = x => (x) > 0 && x % 2 != 0; // boolean expression for 'positive' 'odd' int firstPositiveOdd = Find(predicate2); Console.WriteLine($"\n\nFirst positive odd value (Lambda-style): { firstPositiveOdd }."); // Create an example using a Delegate that takes two int parameters and returns bool // then wire-up the Delegate to a method that collects all matching instances of x // return the count of matches MyPredicate2 mp2 = AreEqual; List <int> matches = MyFindAll(mp2); Console.WriteLine($"\n\nNumber of matching items found: { matches.Count }."); Console.WriteLine("\n\nPress <Enter> to exit. . ."); Console.ReadLine(); }
public Form1() { InitializeComponent(); //1: Create a delegate object to a named method //d1 = new MyPredicate(IsEvenPositive); //Or use a short-cut syntax d1 = IsEvenPositive; //2: Create a delegate to an anonymous method d2 = delegate(int x) { return(x > 0 && x % 2 == 0); }; //3: Create a delegate to a lambda expression d3 = x => x > 0 && x % 2 == 0; d4 = (x, y) => x > 0 && x % 2 == 1 && y >= Math.Pow(x, 2); d5 = (a, b) => (a.Average() + b.Average() / 2); }