Predicate<T> 代理人

定義

条件のセットを定義し、指定されたオブジェクトがその条件を満たしているかどうかを判断するメソッドを表わします。

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 

型パラメーター

T

比較するオブジェクトの型。

この型パラメーターは反変です。 つまり、指定した型、または弱い派生型のいずれかを使用することができます。 共変性および反変性の詳細については、「ジェネリックの共変性と反変性」をご覧ください。

パラメーター

obj
T

このデリゲートで表されるメソッド内で定義された基準と照らし合わせて比較するオブジェクト。

戻り値

Boolean

このデリゲートで表されるメソッド内で定義された基準を obj が満たしている場合は true。それ以外の場合は false

次のコード例では、メソッドと Predicate<T> 共にデリゲートを Array.Find 使用して構造体の Point 配列を検索します。 この例では、名前付きのデリゲートをPredicate<T>明示的に定義し、フィールドの積Point.XPoint.Yが 100,000 を超える場合に返すtrueメソッドFindPointsを割り当てます。predicate 2 番目の例に示すように、型 Predicate<T>のデリゲートを明示的に定義するのではなく、ラムダ式を使用するのが一慣例であることに注意してください。

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

let findPoints (obj: Point) =
    obj.X * obj.Y > 100000

// Create an array of Point structures.
let points = 
    [| Point(100, 200)
       Point(150, 250) 
       Point(250, 375)
       Point(275, 395) 
       Point(295, 450) |]

// Define the Predicate<T> delegate.
let predicate = Predicate<Point> findPoints

// Find the first Point structure for which X times Y
// is greater than 100000.
let first = Array.Find(points, predicate)

// Display the first structure found.
printfn $"Found: X = {first.X}, Y = {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) }
      
      ' 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

次の例は前の例と同じですが、ラムダ式を使用してデリゲートを表す点が Predicate<T> 異なります。 配列の points 各要素は、式が検索条件を満たす要素を見つけるまでラムダ式に渡されます。 この場合、X フィールドと Y フィールドの積が 100,000 を超える場合、ラムダ式が返 true されます。

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

// Create an array of Point structures.
let points = 
    [| Point(100, 200)
       Point(150, 250)
       Point(250, 375)
       Point(275, 395)
       Point(295, 450) |]

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

// Display the first structure found.
printfn $"Found: X = {first.X}, Y = {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

注釈

このデリゲートは、コレクション内の要素を Array 検索するために、いくつかのメソッドと List<T> クラスで使用されます。

通常、 Predicate<T> デリゲートはラムダ式で表されます。 ローカルスコープ変数はラムダ式で使用できるため、コンパイル時に正確に知られていない条件を簡単にテストできます。 これは次の例でシミュレートされています。この例では、ナショナル・Hockey League チームとそれが設立された年に関する情報を含むクラスを定義 HockeyTeam します。 この例では、年を表す整数値の配列を定義し、配列 foundedBeforeYearの 1 つの要素をランダムに割り当てます。これは、この例の Main メソッドに対してローカルスコープの変数です。 ローカルスコープ変数はラムダ式で使用できるため、メソッドに List<T>.FindAll 渡されるラムダ式は、その年以前に設立された各チームのオブジェクトを返 HockeyTeam すことができます。

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
open System

type HockeyTeam =
    { Name: string
      Founded: int }

let rnd = Random()
let teams = ResizeArray()
teams.AddRange 
    [| { Name = "Detroit Red Wings"; Founded = 1926 }
       { Name = "Chicago Blackhawks"; Founded = 1926 }
       { Name = "San Jose Sharks"; Founded = 1991 }
       { Name = "Montreal Canadiens"; Founded = 1909 }
       { Name = "St. Louis Blues"; Founded = 1967 }|]

let years = [| 1920; 1930; 1980; 2000 |]
let foundedBeforeYear = years[rnd.Next(0, years.Length)]
printfn $"Teams founded before {foundedBeforeYear}:"
for team in teams.FindAll(fun x -> x.Founded <= foundedBeforeYear) do
    printfn $"{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

拡張メソッド

GetMethodInfo(Delegate)

指定したデリゲートによって表されるメソッドを表すオブジェクトを取得します。

適用対象

こちらもご覧ください