此方法用于检索与指定谓词定义的条件匹配的所有元素。
句法:
public static T[] FindAll (T[] array, Predicate match);
在此,T是数组元素的类型。
参数:
array: It is the one-dimensional, zero-based array to search.
match: It is the predicate that defines the conditions of the element to search for.
返回值:该方法返回一个数组,其中包含与指定谓词定义的条件相匹配的所有元素(如果找到)。否则,它将返回一个空数组。
异常:如果数组为null或match为null,则此方法将引发ArgumentNullException。
下面的程序说明了Array.FindAll(T [],Predicate的用法
范例1:
// C# program to demonstrate
// FindAll() method
using System;
using System.Collections.Generic;
public class GFG {
// Main Method
public static void Main()
{
try {
// Creating and intializing new the String
String[] myArr = {"Sun", "Mon", "Tue", "Sat"};
// Display the values of the myArr.
Console.WriteLine("Initial Array:");
// calling the PrintIndexAndValues()
// method to print
PrintIndexAndValues(myArr);
// getting a element a with required
// condition using method Find()
String[] value = Array.FindAll(myArr,
element => element.StartsWith("S",
StringComparison.Ordinal));
// Display the value
// of the found element.
Console.WriteLine("Elements are: ");
// printing the Array of String
PrintIndexAndValues(value);
}
catch (ArgumentNullException e) {
Console.Write("Exception Thrown: ");
Console.Write("{0}", e.GetType(), e.Message);
}
}
// Defining the method
// PrintIndexAndValues
public static void PrintIndexAndValues(String[] myArr)
{
for (int i = 0; i < myArr.Length; i++) {
Console.WriteLine("{0}", myArr[i]);
}
Console.WriteLine();
}
}
输出:
Initial Array:
Sun
Mon
Tue
Sat
Elements are:
Sun
Sat
范例2:
// C# program to demonstrate
// FindAll() method
// For ArgumentNullException
using System;
using System.Collections.Generic;
public class GFG {
// Main Method
public static void Main()
{
try {
// Creating and initializing
// new the String
String[] myArr = null;
// getting a element a with
// required condition using
// method Find()
Console.WriteLine("Trying to get the element from a null array");
Console.WriteLine();
String[] value = Array.FindAll(myArr,
element => element.StartsWith("S",
StringComparison.Ordinal));
// Display the value of the found element.
Console.WriteLine("Elements are: ");
// printing the Array of String
PrintIndexAndValues(value);
}
catch (ArgumentNullException e) {
Console.Write("Exception Thrown: ");
Console.Write("{0}", e.GetType(), e.Message);
}
}
// Defining the method
// PrintIndexAndValues
public static void PrintIndexAndValues(String[] myArr)
{
for (int i = 0; i < myArr.Length; i++) {
Console.WriteLine("{0}", myArr[i]);
}
Console.WriteLine();
}
}
输出:
Trying to get the element from a null array
Exception Thrown: System.ArgumentNullException
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.array.findall?view=netframework-4.7.2