Monday, 4 February 2019

What is predicate in C#? And how to use it?

A predicate is a delegate of type System.Predicate that returns either true or false, based upon some condition.
Predicates are used by several methods in Array, including Exists( ), Find( ), FindIndex( ), and FindAll( ). The following program demonstrates using a predicate to determine if an array of integers contains a negative value. If a negative value is found, the program then obtains the first negative value in the array. To accomplish this, the program uses Exists( ) and Find( ).

using System;
class PredDemo
{
    // A predicate method.  
    // It returns true if v is negative.
    static bool IsNeg(int v)
    {
        if (v < 0) return truereturn false;
    }
    static void Main()
    {
        int[] nums = { 1, 4, -1, 5, -9 };
        int[] Search;
        int searchIndex;
        Console.Write("Contents of nums: ");
        foreach (int i in nums)
            Console.Write(i + " ");
        Console.WriteLine();
        // First see if nums contains a negative value. 
        if (Array.Exists(nums, PredDemo.IsNeg))
        {
            Console.WriteLine("find first negative value.");
            int x = Array.Find(nums, PredDemo.IsNeg);
            Console.WriteLine("First negative value is : " + x);
 
            Console.WriteLine("Find all Nagative Values:");
            Search = Array.FindAll(nums, PredDemo.IsNeg);
            foreach(int i in Search)
            {
                //searchIndex = Array.FindIndex(nums, 0, PredDemo.IsNeg);
                Console.WriteLine(i);// +" and its index is:"+searchIndex);
            }
        }
        else
            Console.WriteLine("nums contains no negative values.");
        Console.ReadLine();
    }
  
}

No comments:

Post a Comment