Search code examples
c#arraysindexof

How can I find index of the array in C#?


I am trying to find index of an array.

This is probably easy to do, but I havn't been able to find out how.

From a website, I tried to add a findIndex function, but I am getting an error.
How can I find the index?

namespace exmple.Filters
{
    class dnm2
    {
        public static byte[] Shape(byte[] data)
        {
            byte[] shape = new byte[data.Length];
            byte count = 0;

            for (int i = 0; i < data.Length; i++)
            {
                if (data[i] == 0)
                {
                    shape[i] = (data[i]);

                    int index = shape.findIndex(count);
                    int[] a = {1, 2, 3};
                    int index = a.Indexof((int)3);
                    count += 1;

                }
            }

            return shape;
        }

    public static int findIndex<T>(this T[] array, T item)
    {
        EqualityComparer<T> comparer = EqualityComparer<T>.Default;

        for (int i = 0; i < array.Length; i++)
        {
            if (comparer.Equals(array[i], item)) 
            {
                return i;
            }
        }
 
        return -1;
    }
}


Solution

  • Array.IndexOf() gives you the index of an object in an array. Just make sure you use the same data types, i.e. byte here.

    This is the full code, tested in .NET 4.5.2

    using System;
    
    namespace ConsoleApp2
    {
        class Program
        {
            static void Main()
            {
                byte[] data = { 5, 4, 3, 2, 1 };
                Console.WriteLine(Array.IndexOf(data, (byte)2));
                Console.ReadLine();
            }
        }
    }