Predicate<T> Delegado

Definición

Representa el método que define un conjunto de criterios y determina si el objeto especificado cumple con dichos criterios.Represents the method that defines a set of criteria and determines whether the specified object meets those criteria.

generic <typename T>
public delegate bool Predicate(T obj);
public delegate bool Predicate<in T>(T obj);
public delegate bool Predicate<T>(T obj);
type Predicate<'T> = delegate of 'T -> bool
Public Delegate Function Predicate(Of In T)(obj As T) As Boolean 
Public Delegate Function Predicate(Of T)(obj As T) As Boolean 

Parámetros de tipo

T

Tipo del objeto que se va a comparar.The type of the object to compare.

Este parámetro de tipo es contravariante, es decir, puede usar el tipo que haya especificado o cualquier tipo menos derivado. Si desea obtener más información sobre la covarianza y la contravarianza, consulte Covarianza y contravarianza en genéricos.

Parámetros

obj
T

Objeto que se va a comparar según los criterios definidos en el método representado por este delegado.The object to compare against the criteria defined within the method represented by this delegate.

Valor devuelto

Boolean

Es true si obj cumple los criterios definidos en el método representado por este delegado; de lo contrario, es false.true if obj meets the criteria defined within the method represented by this delegate; otherwise, false.

Ejemplos

En el ejemplo de código siguiente Predicate<T> se usa un delegado con el Array.Find método para buscar en una matriz de Point estructuras.The following code example uses a Predicate<T> delegate with the Array.Find method to search an array of Point structures. En el ejemplo se define explícitamente un Predicate<T> delegado denominado predicate y se le asigna un método denominado FindPoints que devuelve true si el producto de los Point.X Point.Y campos y es mayor que 100.000.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 Point.X and Point.Y fields is greater than 100,000. Tenga en cuenta que es un tipo personalizado para usar una expresión lambda en lugar de definir explícitamente un delegado de tipo Predicate<T> , como se muestra en el segundo ejemplo.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.

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
Imports System.Drawing

Public Class Example
   Public Shared Sub Main()

      ' Create an array of Point structures. 
      Dim points() As Point = { new Point(100, 200), new Point(150, 250), 
                                new Point(250, 375), new Point(275, 395), 
                                new Point(295, 450) }
      
      ' Define the Predicate(Of T) delegate.
      Dim predicate As Predicate(Of Point) = AddressOf Example.FindPoints
      
      ' Find the first Point structure for which X times Y  
      ' is greater than 100000. 
      Dim first As Point = Array.Find(points, predicate)

      ' Display the first structure found.
      Console.WriteLine("Found: X = {0}, Y = {1}", first.X, first.Y)
   End Sub 
   
   Private Shared Function FindPoints(obj As Point) As Boolean
      Return obj.X * obj.Y > 100000
   End Function

End Class 
' The example displays the following output:
'       Found: X = 275, Y = 395

El ejemplo siguiente es idéntico al ejemplo anterior, salvo que usa una expresión lambda para representar el Predicate<T> delegado.The following example is identical to the previous example, except that it uses a lambda expression to represent the Predicate<T> delegate. Cada elemento de la points matriz se pasa a la expresión lambda hasta que la expresión encuentra un elemento que cumple los criterios de búsqueda.Each element of the points array is passed to the lambda expression until the expression finds an element that meets the search criteria. En este caso, la expresión lambda devuelve true si el producto de los campos X e y es mayor que 100.000.In this case, the lambda expression returns true if the product of the X and Y fields is greater than 100,000.

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
Imports System.Drawing

Public Class Example
   Public Shared Sub Main()

      ' Create an array of Point structures. 
      Dim points() As Point = { 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. 
      Dim first As Point = Array.Find(points, 
                                 Function(x) x.X * x.Y > 100000 )

      ' Display the first structure found.
      Console.WriteLine("Found: X = {0}, Y = {1}", first.X, first.Y)
   End Sub 
End Class 
' The example displays the following output:
'       Found: X = 275, Y = 395

Comentarios

Varios métodos de las clases y usan este delegado Array List<T> para buscar elementos en la colección.This delegate is used by several methods of the Array and List<T> classes to search for elements in the collection.

Normalmente, el Predicate<T> delegado se representa mediante una expresión lambda.Typically, the Predicate<T> delegate is represented by a lambda expression. Dado que las variables de ámbito local están disponibles para la expresión lambda, es fácil probar una condición que no se conoce precisamente en tiempo de compilación.Because locally scoped variables are available to the lambda expression, it is easy to test for a condition that is not precisely known at compile time. Esto se simula en el ejemplo siguiente, que define una HockeyTeam clase que contiene información sobre un equipo de la Liga Nacional de hockey y el año en el que se fundó.This is simulated in the following example, which defines a HockeyTeam class that contains information about a National Hockey League team and the year in which it was founded. En el ejemplo se define una matriz de valores enteros que representan años y se asigna aleatoriamente un elemento de la matriz a foundedBeforeYear , que es una variable cuyo ámbito se establece localmente en el método del ejemplo Main .The example defines an array of integer values that represent years, and randomly assigns one element of the array to foundedBeforeYear, which is a variable that is locally scoped to the example's Main method. Dado que las variables de ámbito local están disponibles para una expresión lambda, la expresión lambda que List<T>.FindAll se pasa al método puede devolver un HockeyTeam objeto para cada equipo en el que se basa o antes de ese año.Because locally scoped variables are available to a lambda expression, the lambda expression passed to the List<T>.FindAll method is able to return a HockeyTeam object for each team founded on or before that year.

using System;
using System.Collections.Generic;

public class HockeyTeam
{
   private string _name;
   private int _founded;

   public HockeyTeam(string name, int year)
   {
      _name = name;
      _founded = year;
   }

   public string Name {
      get { return _name; }
   }

   public int Founded {
      get { return _founded; }
   }
}

public class Example
{
   public static void Main()
   {
      Random rnd = new Random();
      List<HockeyTeam> teams = new List<HockeyTeam>();
      teams.AddRange( new HockeyTeam[] { new HockeyTeam("Detroit Red Wings", 1926),
                                         new HockeyTeam("Chicago Blackhawks", 1926),
                                         new HockeyTeam("San Jose Sharks", 1991),
                                         new HockeyTeam("Montreal Canadiens", 1909),
                                         new HockeyTeam("St. Louis Blues", 1967) } );
      int[] years = { 1920, 1930, 1980, 2000 };
      int foundedBeforeYear = years[rnd.Next(0, years.Length)];
      Console.WriteLine("Teams founded before {0}:", foundedBeforeYear);
      foreach (var team in teams.FindAll( x => x.Founded <= foundedBeforeYear))
         Console.WriteLine("{0}: {1}", team.Name, team.Founded);
   }
}
// The example displays output similar to the following:
//       Teams founded before 1930:
//       Detroit Red Wings: 1926
//       Chicago Blackhawks: 1926
//       Montreal Canadiens: 1909
Imports System.Collections.Generic

Public Class HockeyTeam
   Private _name As String
   Private _founded As Integer
   
   Public Sub New(name As String, year As Integer)
      _name = name
      _founded = year
   End Sub

   Public ReadOnly Property Name As String
      Get
         Return _name
      End Get
   End Property

   Public ReadOnly Property Founded As Integer
      Get 
         Return _founded
      End Get   
   End Property
End Class

Module Example
   Public Sub Main()
      Dim rnd As New Random()
      Dim teams As New List(Of HockeyTeam)()
      teams.AddRange( { new HockeyTeam("Detroit Red Wings", 1926), 
                        new HockeyTeam("Chicago Blackhawks", 1926),
                        new HockeyTeam("San Jose Sharks", 1991),
                        new HockeyTeam("Montreal Canadiens", 1909),
                        new HockeyTeam("St. Louis Blues", 1967) } )
      Dim years() As Integer = { 1920, 1930, 1980, 2000 }
      Dim foundedBeforeYear As Integer = years(rnd.Next(0, years.Length))
      Console.WriteLine("Teams founded before {0}:", foundedBeforeYear)
      For Each team in teams.FindAll( Function(x) x.Founded <= foundedBeforeYear )
         Console.WriteLine("{0}: {1}", team.Name, team.Founded)
      Next   
   End Sub
End Module
' The example displays output similar to the following:
'       Teams founded before 1930:
'       Detroit Red Wings: 1926
'       Chicago Blackhawks: 1926
'       Montreal Canadiens: 1909

Métodos de extensión

GetMethodInfo(Delegate)

Obtiene un objeto que representa el método representado por el delegado especificado.Gets an object that represents the method represented by the specified delegate.

Se aplica a

Consulte también