C# - delegate Predicate<T>

c#

Solution

There are several use cases where its useful to allow the caller to provide a function that returns `true` or `false`. The `Predicate<T>` type is a way to do this. This is no different than `Func<T, bool>` (except `Predicate<T>` was available in earlier versions of C#).

A simple (and contrived 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 `FindAll` method returns an array of all items that match the condition. In this case, all the strings that start with "h". The `Predicate` is `s.StartsWith("h")`.

The useful thing here, is that the `Array` class knows how to search through all its elements, and create a new array containing only the elements that match. This part of the algorithm is common to many pieces of code. The part that is not common, is the matching criteria, which will vary based on the requirements of the specific piece of code. Thus the caller specifies that part of the logic, and passes it in as a `Predicate`.

You can handle it in a "nested" style. `Func<Predicate<T>>` means you are declaring a function that returns a `Predicate<T>`. Are you sure this is what you want? What are you trying to achieve?

Problem

What is the use of delegate `Predicate<T>` ,Shall i handle it as nested style like `Func<Predicate<T>>`?. Simple example please.

Original source