Array.Find<T>(T[], Predicate<T>) 方法

定义

搜索与指定谓词定义的条件匹配的元素,并返回整个 Array中的第一个匹配项。

C#
public static T Find<T>(T[] array, Predicate<T> match);
C#
public static T? Find<T>(T[] array, Predicate<T> match);

类型参数

T

数组元素的类型。

参数

array
T[]

要搜索的一维从零开始的数组。

match
Predicate<T>

定义要搜索的元素条件的谓词。

返回

T

与指定谓词定义的条件匹配的第一个元素(如果找到);否则,类型为 T的默认值。

例外

array null

-或-

match null

示例

以下示例使用具有 Find 泛型方法的 Predicate<T> 委托来搜索 Point 结构的数组。 如果 X 和 Y 字段的乘积大于 100,000,则委托表示的方法 ProductGT10返回 trueFind 方法调用数组的每个元素的委托,返回满足测试条件的第一个点。

备注

Visual Basic、C# 和 F# 用户不必显式创建委托或指定泛型方法的类型参数。 编译器从提供的方法参数中确定必要的类型。

C#
using System;
using System.Drawing;

public class Example
{
    public static void Main()
    {
        // Create an array of five 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, ProductGT10);

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

    // Return true if X times Y is greater than 100000.
    private static bool ProductGT10(Point p)
    {
        return p.X * p.Y > 100000;
    }
}
// The example displays the following output:
//       Found: X = 275, Y = 395

通常使用 lambda 表达式,而不是使用必要的签名显式定义方法、实例化 Predicate<T> 委托并将委托传递给 Find 方法。 以下示例与上一个示例相同,只不过它使用 lambda 表达式作为 match 参数。

C#
using System;
using System.Drawing;

public class Example
{
    public static void Main()
    {
        // Create an array of five 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, p => p.X * p.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

注解

Predicate<T> 是方法或 lambda 表达式的委托,如果传递给该方法或 lambda 表达式的对象与委托或 lambda 表达式中定义的条件匹配,则返回 truearray 的元素分别传递给 Predicate<T>,从第一个元素开始,最后一个元素结束。 找到匹配项时,将停止处理。

此方法是 O(n) 操作,其中 narrayLength

在 F# 中,可以改用 Array.find 函数。

适用于

产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

另请参阅