C# Array.FindIndex Method

Find icon

Imperative searching of arrays is both common and efficient. However, in some contexts, using a declarative method call to locate an index with a higher-order procedure is beneficial. The Array.FindIndex method, and its opposite Array.FindLastIndex, use a predicate function to search for matching elements.

This C# example program uses the Array.FindIndex method. It searches an array.

Example

Note

To begin, this program example declares and allocates an array of four integers upon the managed heap. After this, the Array.FindIndex and Array.FindLastIndex methods are invoked.

Please pay special attention to the syntax of the parameters to these two methods. The first parameter is the array reference itself; the second parameter is in the form of a lambda expression, which fits the requirement of a predicate as well. If the right-side expression of the lambdas evaluates to true, then the predicate is true and the element matches. Finally, the results of the program are written to the screen.

Program that uses Array.FindIndex method [C#]

using System;

class Program
{
    static void Main()
    {
	// Use this input array.
	int[] array = { 5, 6, 7, 6 };

	// Use FindIndex method with predicate.
	int index1 = Array.FindIndex(array, item => item == 6);
	// Use LastFindIndex method with predicate.
	int index2 = Array.FindLastIndex(array, item => item == 6);

	// Write results.
	Console.WriteLine("{0} = {1}", index1, array[index1]);
	Console.WriteLine("{0} = {1}", index2, array[index2]);
    }
}

Output

1 = 6
3 = 6
Note (please read)

Locating a certain element. The two lambda expressions both are used to locate elements with a value of exactly six. The FindIndex method searches from the first to the last element, so returns an index of 1. The FindLastIndex method, in contrast, searches from last to first, so returns an index of 3.

Summary

Higher-order procedures such as the Array.FindIndex method shown here provide a greater level of procedural fluency in some contexts. It is possible to reuse more logic throughout your program by only changing the predicate or lambda expression. In essence, by collapsing behavior into a data structure, you can build sophisticated abstractions that more closely model your program's purpose.

Structure and Interpretation of Computer Programs Array Types
.NET