此方法用於搜索與指定謂詞定義的條件匹配的元素,並返回整個Array中的最後一個匹配項。
用法:
public static T FindLast<T> (T[] array, Predicate<T> match);
參數:
-
array:它是要搜索的一維,從零開始的數組。
match:謂詞定義了要搜索的元素的條件。
返回值:如果找到,則此方法返回與指定謂詞定義的條件相匹配的最後一個元素,否則返回類型T的默認值。
異常:如果數組為null或match為null,則此方法引發ArgumentNullException。
以下示例程序旨在說明Array.FindLast(T [],Predicate)方法的用法:
示例1:
// C# program to demonstrate
// Array.FindLast(T[], Predicate<T>)
// 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<T>)
// 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
參考:
相關用法
- C# DateTimeOffset.Add()用法及代碼示例
- C# String.Contains()用法及代碼示例
- C# Math.Sin()用法及代碼示例
- C# Math.Cos()用法及代碼示例
- C# Dictionary.Add()用法及代碼示例
- C# Math.Tan()用法及代碼示例
- C# Math.Abs()方法用法及代碼示例
- C# Math.Exp()用法及代碼示例
- C# Math.Abs()函數用法及代碼示例
注:本文由純淨天空篩選整理自RohitPrasad3大神的英文原創作品 C# | Array.FindLast() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。