TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Array.FindIndex Method

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

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.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf