- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Array.LastIndexOf() Method in C#
The Array.LastIndexOf() method in C# is used to search for the specified object and returns the index of the last occurrence within the entire one-dimensional Array.
Syntax
public static int LastIndexOf (Array arr, object val);
Above, arr is the one-dimensional Array to search, whereas val is the object to locate in arr.
Example
using System; public class Demo { public static void Main() { string[] strArr = {"John", "Tim", "Fedric", "Gary", "Harry", "Damien", "David", "Harry"}; Array.Sort(strArr); Console.WriteLine("Array elements..."); foreach(string s in strArr) { Console.WriteLine(s); } Console.Write("Element Gary is at index = " + Array.BinarySearch(strArr, "Gary")); Console.Write("
Element Tom is at index = " + Array.BinarySearch(strArr, "Tom")); Console.Write("
Last index of element Harry = " + Array.LastIndexOf(strArr, "Harry")); } }
Output
Array elements... Damien David Fedric Gary Harry Harry John Tim Element Gary is at index = 3 Element Tom is at index = -9 Last index of element Harry = 5
Example
using System; public class Demo { public static void Main() { int[] intArr = {5, 10, 15, 20, 15, 25, 30}; Array.Sort(intArr); Console.WriteLine("Array elements..."); foreach(int i in intArr) { Console.WriteLine(i); } Console.Write("Element 25 is at index = " + Array.BinarySearch(intArr, 20)); Console.Write("
Last index of element 15 = " + Array.LastIndexOf(intArr, 15)); Console.Write("
Last index of element 50 = " + Array.LastIndexOf(intArr, 50)); } }
Output
Array elements... 5 10 15 15 20 25 30 Element 25 is at index = 4 Last index of element 15 = 3 Last index of element 50 = -1
Advertisements