List FindIndex searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the first occurrence within the range of elements in the List that starts at the specified index and contains the specified number of elements
Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the first occurrence within the entire List<T>
Example 1: Get index number of given a number
1 2 3 4 5 6 7 8 9 |
List<int> numbers = new List<int>() { 10, 45, 25, 10, 1, 30, 45, 125 }; int numberIndex = numbers.FindIndex(x => x == 25); Console.WriteLine("Number 25 {0}. place",numberIndex); // Number 25 is 3. place Console.ReadLine(); |
Example 2: Get index number of given string
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
List<string> names = new List<string>(); names.Add("Mark"); names.Add("Tom"); names.Add("Dany"); names.Add("Dubrovk"); names.Add("Mehde"); names.Add("Candy"); int numberIndex = names.FindIndex(x => x == "Tom"); Console.WriteLine("Tom is {0}. place",numberIndex); // Tom is at 2. place Console.ReadLine(); |
Example 3: We can start searching from a specific start and can give a custom range
1 2 3 4 5 6 7 8 9 10 11 |
List<int> numbers = new List<int>() { 10, 45, 25, 10, 1, 30, 45, 125 }; int start = 2; int count = 3; int search = 10; int numberIndex = numbers.FindIndex(start , count ,x => x == search); Console.WriteLine( numberIndex); //3 Console.ReadLine(); |
Example 4: Find index number of an object (C# Findindex Predicate an object with Example)
Book class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
class Book { string title; string genre; int price; public string Title { get => title; set => title = value; } public string Genre { get => genre; set => genre = value; } public int Price { get => price; set => price = value; } public Book(string t, string g, int p) { title = t; genre = g; price = p; } } |
Main:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
List<Book> Books = new List<Book>() { new Book("Broken hearts","Romance",12), new Book("Nothing in my life","Guide",2), new Book("Love for love", "Romance", 10), new Book("Spain", "Travel", 8), new Book("Fruits", "Cookbooks", 25) }; string genre = "Guide"; int numberIndex = Books.FindIndex(x => x.Genre==genre); Console.WriteLine( numberIndex); //1 Console.ReadLine(); |
Example 5: C# List FindIndex returns -1 if not found
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
List<Book> Books = new List<Book>() { new Book("Broken hearts","Romance",12), new Book("Nothing in my life","Guide",2), new Book("Love for love", "Romance", 10), new Book("Spain", "Travel", 8), new Book("Fruits", "Cookbooks", 25) }; string genre = "Science"; int numberIndex = Books.FindIndex(x => x.Genre==genre); Console.WriteLine( numberIndex); //-1 Console.ReadLine(); |