Use of Predicate with Methods of Array in C#

In this article I am going to explain about use of predicate with methods of Array in C#.
  • 3678

Predicate in C# is a Delegate which represents the method that defines a set of criteria and determines whether the specified object meets those criteria. We can use this delegate with several methods of array. It is used to search elements in collections.

Syntax of defining delegates 

public delegate bool Predicate<in T>
(
T obj
)

using System.Collections;

 

public class Class1

{

     public static void Main()

    {

        int[] zArray = { 1, 2, 3, 1, 2, 3, 1, 2, 3 };

        Predicate<int> match = new Predicate<int>(MethodA<int>);

        int[] answers = Array.FindAll(zArray, match);

        foreach (int answer in answers)

        {

            Console.WriteLine(answer); 

        }

        Console.ReadKey();

    }

 

    public static bool MethodA<T>(T number) where T : IComparable

    {

        int result = number.CompareTo(3);

        return result == 0;

    }

}


Output

bool predicate array.gif

Ask Your Question 

Got a programming related question? You may want to post your question here
 

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.