C # - delegate Predicate <T>

What is the use of a delegate Predicate<T>, I have to treat it as a nested style like

Func<Predicate<T>>? A simple example.

+3
source share
3 answers

There are several use cases where it is useful for the caller to provide a function that returns trueor false. Type Predicate<T>is the way to do this. This is no different from Func<T, bool>(except Predicate<T>available in earlier versions of C #).

A simple (and far-fetched example):

string[] strings = new string[] { "hello", "goodbye", "how are you" };

Array.FindAll(strings, delegate(string s)
                           {
                               return s.StartsWith("h");
                           });

or, lambda style:

Array.FindAll(strings, s => s.StartsWith("h"));

The method FindAllreturns an array of all elements matching the condition. In this case, all lines starting with "h". Predicate s.StartsWith("h").

, Array , , , . . , , - , . , Predicate.

"" . Func<Predicate<T>> , , Predicate<T>. , , ? ?

+10
// Make a list of integers.
List<int> list = new List<int>();
list.AddRange(new int[] { 20, 1, 4, 8, 9, 44 });
// Call FindAll() using traditional delegate syntax.
Predicate<int> callback = new Predicate<int>(IsEvenNumber);
List<int> evenNumbers = list.FindAll(callback);

// Target for the Predicate<> delegate.
static bool IsEvenNumber(int i)
{
    // Is it an even number?
    return (i % 2) == 0;
}
+2

, (, true false). ? , , , True False, , .

0

Source: https://habr.com/ru/post/1715758/


All Articles