Array search with IndexOf methods

In this chapter you will learn:

  1. How to search an array with IndexOf and LastIndexOf method
  2. Search element index of int array

Use IndexOf and LastIndexOf methods

using System;//j  av a2  s. c  o  m

class MainClass
{

  public static void Main()
  {
    string[] stringArray = {"Hello", "to", "everyone", "Hello", "all"};
    Console.WriteLine("stringArray:");
    for (int i = 0; i < stringArray.Length; i++)
    {
      Console.WriteLine("stringArray[" + i + "] = " + stringArray[i]);
    }
    int index = Array.IndexOf(stringArray, "Hello");
    Console.WriteLine("Array.IndexOf(stringArray, \"Hello\") = " + index);
    index = Array.LastIndexOf(stringArray, "Hello");
    Console.WriteLine("Array.LastIndexOf(stringArray, \"Hello\") = " + index);

  }

}

The code above generates the following result.

Search index of int array

using System;/*j  av a  2s .  c o  m*/

class MainClass
{

  public static void Main()
  {
    int[] intArray = {1, 2, 1, 3};
    Console.WriteLine("intArray:");
    for (int i = 0; i < intArray.Length; i++)
    {
      Console.WriteLine("intArray[" + i + "] = " +
        intArray[i]);
    }

    
    int index = Array.IndexOf(intArray, 1);
    Console.WriteLine("Array.IndexOf(intArray, 1) = " + index);
    index = Array.LastIndexOf(intArray, 1);
    Console.WriteLine("Array.LastIndexOf(intArray, 1) = " + index);
  }

}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. Use the BinarySearch() method to search int Array for the number 5
  2. BinarySearch() returns a negative value in case of not found
  3. Binary search array element
  4. Use the BinarySearch() method to search charArray for 'o'
Home » C# Tutorial » Array
Array
Array loop
Array dimension
Jagged Array
Array length
Array Index
Array rank
Array foreach loop
Array ForEach Action
Array lowerbound and upperbound
Array Sort
Array search with IndexOf methods
Array binary search
Array copy
Array clone
Array reverse
Array ConvertAll action
Array Find
Array SequenceEqual