Array.LastIndexOf Method in C# | Set – 2
Last Updated :
14 Aug, 2021
Array.LastIndexOf method is used to find the index of the last occurrence of a value in a one-dimensional Array or in a portion of the Array. It starts the search from the last element of an array. It returns the index of the element that contains the specified value. There are 6 methods in the overload list of this method as follows:
- LastIndexOf(Array, Object)
- LastIndexOf(Array, Object, Int32)
- LastIndexOf(Array, Object, Int32, Int32)
- LastIndexOf<T>(T[], T)
- LastIndexOf<T>(T[], T, Int32)
- LastIndexOf<T>(T[], T, Int32, Int32)
Here, we will discuss the last three methods.
LastIndexOf<T>(T[], T) Method
This method searches for the specified object and returns the index of the last occurrence within the entire 1-D Array.
Syntax: public static int LastIndexOf<T> (T[] arr, T value);
Here, T is the type of the elements of the array.
Parameters:
arr: It is the one-dimensional array.
value: It is the object to locate in array.
Return Value: If the object is found then the zero-based index of the last occurrence of value within the entire array is returned, otherwise, -1.
Exception: This method will give the ArgumentNullException if the array is null.
Example:
csharp
// C# program to demonstrate the
// Array.LastIndexOf<T>(T[], T)
using System;
class GFG {
// Main Method
public static void Main()
{
// array elements
string[] arr = { "ABC",
"EFG",
"GHI",
"LMO",
"STW",
"XYZ",
"QRS" };
Console.WriteLine("Original Array");
foreach(string g in arr)
{
Console.WriteLine("Original array" + g);
}
// here the object is STW
Console.WriteLine("\nThe position of STW is " +
Array.LastIndexOf(arr, "STW"));
}
}
Output: Original Array
Original arrayABC
Original arrayEFG
Original arrayGHI
Original arrayLMO
Original arraySTW
Original arrayXYZ
Original arrayQRS
The position of STW is 4
LastIndexOf<T>(T[], T, Int32) Method
This method searches for the specified object and returns the index of the last occurrence within the range of elements in the Array that extends from the first element to the specified index.
Syntax: public static int LastIndexOf<T> (T[] arr, T value, int start);
Here, T is the type of the elements of the array.
Parameters:
arr: It is the one-dimensional array.
value: It is the object to locate in array
start: It is the zero-based starting index of the backward search.
Exceptions:
- ArgumentNullException: If the array is null.
- ArgumentOutOfRangeException: If the "start" is outside the range of valid indexes for array.
Example:
csharp
// C# program to demonstrate the
// Array.LastIndexOf<T>(T[], T, Int32)
using System;
class GFG {
// Main Method
public static void Main()
{
// array elements
string[] arr = { "ABC",
"EFG",
"GHI",
"LMO",
"STW",
"XYZ",
"QRS" };
Console.WriteLine("Original Array");
foreach(string g in arr)
{
Console.WriteLine(g);
}
// Here the object is STW
// the search starts from index 5
Console.WriteLine("\nthe position of STW is " +
Array.LastIndexOf(arr, "STW", 5));
}
}
Output: Original Array
ABC
EFG
GHI
LMO
STW
XYZ
QRS
the position of STW is 4
LastIndexOf<T>(T[], T, Int32, Int32) Method
This method searches for the specified object and returns the index of the last occurrence within the range of elements in the Array that contains the specified number of elements and ends at the specified index.
Syntax: public static int LastIndexOf<T> (T[] arr, T value, int start, int count);
Parameters:
arr: It is the one-dimensional array.
value: It is the object to locate in array.
start: It is the zero-based starting index of the backward search.
count: It is the number of elements in the section to search.
Return Value: This method will return zero-based index of the last occurrence of value within the range of elements in the array that contains the number of elements specified in the count and ends at start if found; otherwise, -1.
Exceptions:
- ArgumentNullException: If the array is null.
- ArgumentOutOfRangeException: If the start is outside the range of valid indexes for array or start and count do not specify a valid section in array.
Example:
csharp
// C# program to demonstrate the
// Array.LastIndexOf(T[], T,
// Int32, Int32)
using System;
class GFG {
// Main Method
public static void Main()
{
// array elements
string[] arr = { "ABC",
"EFG",
"GHI",
"LMO",
"STW",
"XYZ",
"QRS" };
Console.WriteLine("Original Array");
foreach(string g in arr)
{
Console.WriteLine(g);
}
// here the object is STW
// the search starts from index 5
// the search happens backward from
// index 5 to another 2 index
Console.WriteLine("\nthe position of STW is " +
Array.LastIndexOf(arr, "STW", 5, 2));
}
}
Output: Original Array
ABC
EFG
GHI
LMO
STW
XYZ
QRS
the position of STW is 4
Reference:
Similar Reads
Decorators in Python In Python, decorators are a powerful and flexible way to modify or extend the behavior of functions or methods, without changing their actual code. A decorator is essentially a function that takes another function as an argument and returns a new function with enhanced functionality. Decorators are
10 min read
AVL Tree Data Structure An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. The absolute difference between the heights of the left subtree and the right subtree for any node is known as the balance factor of
4 min read
Sliding Window Technique Sliding Window Technique is a method used to solve problems that involve subarray or substring or window. The main idea is to use the results of previous window to do computations for the next window. This technique is commonly used in algorithms like finding subarrays with a specific sum, finding t
13 min read
What is a Neural Network? Neural networks are machine learning models that mimic the complex functions of the human brain. These models consist of interconnected nodes or neurons that process data, learn patterns, and enable tasks such as pattern recognition and decision-making.In this article, we will explore the fundamenta
14 min read
Read JSON file using Python The full form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Pytho
4 min read
ArrayList in Java Java ArrayList is a part of the collections framework and it is a class of java.util package. It provides us with dynamic-sized arrays in Java. The main advantage of ArrayList is that, unlike normal arrays, we don't need to mention the size when creating ArrayList. It automatically adjusts its capac
9 min read
Multithreading in Python This article covers the basics of multithreading in Python programming language. Just like multiprocessing , multithreading is a way of achieving multitasking. In multithreading, the concept of threads is used. Let us first understand the concept of thread in computer architecture. What is a Process
8 min read
Two Pointers Technique Two pointers is really an easy and effective technique that is typically used for Two Sum in Sorted Arrays, Closest Two Sum, Three Sum, Four Sum, Trapping Rain Water and many other popular interview questions. Given a sorted array arr (sorted in ascending order) and a target, find if there exists an
11 min read
Python Match Case Statement Introduced in Python 3.10, the match case statement offers a powerful mechanism for pattern matching in Python. It allows us to perform more expressive and readable conditional checks. Unlike traditional if-elif-else chains, which can become unwieldy with complex conditions, the match-case statement
7 min read
Regression in machine learning Regression in machine learning refers to a supervised learning technique where the goal is to predict a continuous numerical value based on one or more independent features. It finds relationships between variables so that predictions can be made. we have two types of variables present in regression
5 min read