TheDeveloperBlog.com


C# Array.FindIndex Method

Array.FindIndex. Imperative searching of arrays is common and efficient. But in some contexts, using a declarative method call to locate an index with a higher-order procedure is beneficial. Array.FindIndex and FindLastIndex are helpful.


Example. 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.

Int Array

The first argument is the array reference. The second argument is in the form of a lambda expression, which fits the requirement of a predicate. If the right-side expression evaluates to true, the element matches.

Lambda Expression

Finally: The results of the program are written to the screen with the Console.WriteLine method.

Console.WriteLine
C# program that uses Array.FindIndex method

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

The lambda expressions are used to locate elements with a value of 6. FindIndex searches from the first to the last element—it returns an index of 1. FindLastIndex, in contrast, searches from last to first—it returns an index of 3.


Summary. Higher-order procedures such as the Array.FindIndex method 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.

Array.Find

Thus: By collapsing behavior into a data structure, we build sophisticated abstractions that more closely model a program's purpose.