Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Tìm Phần Tử Khớp Điều Kiện Và Trả Về Chỉ Số Zero-Based Cuối Cùng Trong List C#


Để tìm phần tử khớp điều kiện và trả về chỉ số zero-based của lần xuất hiện cuối cùng trong toàn bộ List, mã như sau −

Ví Dụ

using System; 
using System.Collections.Generic; 
public class Demo { 
    private static bool demo(int i) { 
        return ((i % 10) == 0); 
    } 
    public static void Main(String[] args) { 
        List<int> list = new List<int>(); 
        list.Add(200); 
        list.Add(215); 
        list.Add(310); 
        list.Add(500); 
        list.Add(600); 
        Console.WriteLine("List elements..."); 
        foreach (int i in list) { 
            Console.WriteLine(i); 
        } 
        Console.WriteLine("Last Index of the satisfying condition = "+list.FindLastIndex(demo)); 
    } 
}

Kết Quả

Điều này sẽ tạo ra đầu ra sau −

List elements... 
200 
215 
310 
500 
600 
Last Index of the satisfying condition = 4

Ví Dụ

Hãy xem ví dụ khác −

using System; 
using System.Collections.Generic; 
public class Demo { 
    private static bool demo(int i) { 
        return ((i % 2) == 0); 
    } 
    public static void Main(String[] args) { 
        List<int> list = new List<int>(); 
        list.Add(200); 
        list.Add(215); 
        list.Add(310); 
        list.Add(500); 
        list.Add(655); 
        Console.WriteLine("List elements..."); 
        foreach (int i in list) { 
            Console.WriteLine(i); 
        } 
        Console.WriteLine("Last Index of the satisfying condition = "+list.FindLastIndex(demo)); 
    } 
}

Kết Quả

Điều này sẽ tạo ra đầu ra sau −

List elements... 
200 
215 
310 
500 
655 
Last Index of the satisfying condition = 3