c# Predicate<​T> Delegate 找第一个符合定义要求的元素

Predicate<​T> Delegate

Represents the method that defines a set of criteria and determines whether the specified object meets those criteria.

C#
public delegate bool Predicate<in T>(T obj);
Type Parameters
T

The type of the object to compare.

Parameters
obj

The object to compare against the criteria defined within the method represented by this delegate.

Inheritance
Predicate<T>

Examples

The following code example uses a Predicate<T> delegate with the System.Array.Find method to search an array of Point structures. The example explicitly defines a Predicate<T> delegate named predicate and assigns it a method named FindPoints that returns true if the product of the System.Drawing.Point.X and System.Drawing.Point.Y fields is greater than 100,000. Note that it is customary to use a lambda expression rather than to explicitly define a delegate of type Predicate<T>, as the second example illustrates.

C#
using System;
using System.Drawing;

public class Example
{
   public static void Main()
   {
      // Create an array of Point structures.
      Point[] points = { new Point(100, 200), 
                         new Point(150, 250), new Point(250, 375), 
                         new Point(275, 395), new Point(295, 450) };

      // Define the Predicate<T> delegate.
      Predicate<Point> predicate = FindPoints;
      
      // Find the first Point structure for which X times Y  
      // is greater than 100000. 
      Point first = Array.Find(points, predicate);

      // Display the first structure found.
      Console.WriteLine("Found: X = {0}, Y = {1}", first.X, first.Y);
   }

   private static bool FindPoints(Point obj)
   {
      return obj.X * obj.Y > 100000;
   }
}
// The example displays the following output:
//        Found: X = 275, Y = 395

The following example is identical to the previous example, except that it uses a lambda expression to represent the Predicate<T> delegate. Each element of the points array is passed to the lambda expression until the expression finds an element that meets the search criteria. In this case, the lambda expression returns true if the product of the X and Y fields is greater than 100,000.

C#
using System;
using System.Drawing;

public class Example
{
   public static void Main()
   {
      // Create an array of Point structures.
      Point[] points = { new Point(100, 200), 
                         new Point(150, 250), new Point(250, 375), 
                         new Point(275, 395), new Point(295, 450) };

      // Find the first Point structure for which X times Y  
      // is greater than 100000. 
      Point first = Array.Find(points, x => x.X * x.Y > 100000 );

      // Display the first structure found.
      Console.WriteLine("Found: X = {0}, Y = {1}", first.X, first.Y);
   }
}
// The example displays the following output:
//        Found: X = 275, Y = 395
posted @ 2017-07-02 23:05  $JackChen  阅读(208)  评论(0编辑  收藏  举报