此方法用于搜索与指定谓词定义的条件匹配的元素,并返回整个Array中的最后一个匹配项。
句法:
public static T FindLast (T[] array, Predicate match);
参数:
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.
返回值:如果找到,则此方法返回与指定谓词定义的条件相匹配的最后一个元素,否则返回类型T的默认值。
异常:如果数组为null或match为null,则此方法将引发ArgumentNullException。
下面的程序说明了Array.FindLast(T [],Predicate的用法
范例1:
// C# program to demonstrate
// Array.FindLast(T[], Predicate)
// 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", "Son", "Tue", "Thu"};
// Display the values of the myArr.
Console.WriteLine("Initial Array:");
// calling the PrintIndexAndValues()
// method to print
PrintIndexAndValues(myArr);
// getting a last element with required
// condition using method FindLast()
string value = Array.FindLast(myArr,
element => element.StartsWith("S",
StringComparison.Ordinal));
// Display the value of
// the found element.
Console.Write("Last occurrence: ");
// printing the string
// following the condition
Console.Write("{0}", 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
Son
Tue
Thu
Last occurrence: Son
范例2:
// C# program to demonstrate
// Array.FindLast(T[], Predicate)
// Method
using System;
using System.Collections.Generic;
public class GFG {
// Main Method
public static void Main()
{
try {
// Creating and intializing
// new Array String with null
String[] myArr = null;
// getting a last element with required
// condition using method FindLast()
string value = Array.FindLast(myArr,
element => element.StartsWith("S",
StringComparison.Ordinal));
// Display the value of
// the found element.
Console.Write("Last occurrence: ");
// printing the string
// following the condition
Console.Write("{0}", 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();
}
}
输出:
Exception Thrown: System.ArgumentNullException
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.array.findlast?view=netframework-4.7.2