How can I use indexOf to find all occurrences of an element in an array?

I'm implementing a program to find the first occurrence of an element in an array, but I can't figure out how to find all the occurrences.

class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter amount of elements in array:");
            int n = Convert.ToInt32(Console.ReadLine());
            int[] array = new int[n];
            Random rand = new Random();
            for (int i = 0; i < n; i++)
            {
                array[i] = rand.Next(0, 10);
                Console.Write(array[i] + " ");
            }
            Console.WriteLine("\nEnter the value you are looking for:");
            int m = Convert.ToInt32(Console.ReadLine());
            int index = Array.IndexOf(array, m);
            if (index == -1)
               Console.WriteLine("There is no desired number.");
            else
               Console.Write("The first time value on position [{0}] ", index);



            Console.ReadKey();
        }
Author: Wixiam, 2019-07-18

3 answers

int index = -1;
do
{
    index = Array.IndexOf(array, m, index + 1);
    if(index != -1)
        Console.WriteLine(index);
}
while(index != -1);

That's probably how it should work. The third parameter in IndexOf specifies the position from which to start the search. That is, here we start looking for each iteration not from the beginning, but from the place where we left off last time. This code will output the indexes of all occurrences.

 0
Author: V-Mor, 2019-07-18 09:00:29

LINQ single line

var arr = new int[] {1, 2, 3, 4, 5, 6, 3, 4, 5, 6, 2,3, 4, 5};
var target = 3;

var indexes = arr.Select((a,i)=>(a,i)).Where(x=>x.a == target).Select(x=>x.i).ToArray();

foreach(var index in indexes) Console.WriteLine(index);

Output

2
6
11
 1
Author: tym32167, 2019-07-18 08:26:51

Perhaps I will now give not the most universal way. I think that it can be easier to do through LINQ.

Creating an empty array to store the occurrence indexes:

List<int> arr = new List<int>();

We go through the original array and check for a match

for(int i = 0; i < array.Length; i++)
    if(array[i] == m)
       arr.Add(i);
 0
Author: alladuh, 2019-07-18 08:26:53