Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

เมธอด Array.TrueForAll() ใน C#

เมธอด Array.TrueForAll() ใน C# ใช้ตรวจสอบว่าทุกองค์ประกอบในอาร์เรย์ตรงตามเงื่อนไขที่กำหนดโดย predicate ที่ระบุหรือไม่

ไวยากรณ์

public static bool TrueForAll<T> (T[] array, Predicate<T> match);

ตัวอย่าง

ตัวอย่าง: ตรวจสอบว่าทุกข้อความในอาร์เรย์ขึ้นต้นด้วย 'b'

using System; 
public class Demo{ 
    public static void Main(){ 
        Console.WriteLine("Array elements..."); 
        string[] arr = { "bike", "bus" }; 
        for (int i = 0; i < arr.Length; i++){ 
            Console.Write("{0} ", arr[i]); 
        } 
        Console.WriteLine(); 
        int lastIndex = Array.LastIndexOf(arr, "bus"); 
        Console.WriteLine("Last Occurrence of element bus is at index = " + lastIndex); 
        bool res = Array.TrueForAll(arr, ele => ele.StartsWith("b", StringComparison.Ordinal)); 
        if (res) 
            Console.Write("Every element in the array matches the conditions defined by the specified predicate."); 
        else 
            Console.Write("Not every element in the array matches the conditions defined by the specified predicate"); 
    } 
}

ผลลัพธ์

Array elements... bike bus 
Last Occurrence of element bus is at index = 1 
Every element in the array matches the conditions defined by the specified predicate