C# List Find, FindLast, FindIndex, FindLastIndex

In this source code example, we will demonstrate the usage of List Find, FindLast, FindIndex, and FindLastIndex in C#.

The Find method returns the first occurrence of the element that matches the given predicate. 

The FindLast method returns the last occurrence of the element that matches the given predicate.

The FindIndex method returns the index of the first occurrence of the element that matches the given predicate. 

The FindLastIndex method returns the index of the last occurrence of the element that matches the given predicate.

C# List Find, FindLast, FindIndex, FindLastIndex Example

The following example uses Find, FindLast, FindIndex, and FindLastIndex methods to find elements and indexes.
using System;
using System.Collections.Generic;

public class ListDemo
{
    public static void Main(string[] args)
    {
        var nums = new List<int> { 6, -2, 1, 5, 4, 3, 2, 9, -1, 7 };
        
        var found = nums.Find(e => e < 0);
        Console.WriteLine(found);
        
        var found2 = nums.FindIndex(e => e < 0);
        Console.WriteLine(found2);
        
        var found3 = nums.FindLast(e => e < 0);
        Console.WriteLine(found3);
        
        var found4 = nums.FindLastIndex(e => e < 0);
        Console.WriteLine(found4);
        
    }
}

Output:

-2
1
-1
8

Related C# List Examples


Comments