none
How Can I Find indices of an element in 2D array??

    Question

  • int index=Array.indexOf(MyArray,(Object Array)sender);

    is not working in this case what do I do??

    I'm trying to find the indices of an element in 2D array, how has raise the event. 


    • Edited by HassnainAli Thursday, December 26, 2013 7:48 PM
    Thursday, December 26, 2013 7:47 PM

Answers

  • Create a class with a method to find  index. Check this

    public static class ExtensionMethods
    {
        public static Tuple<int, int> CoordinatesOf<T>(this T[,] matrix, T value)
        {
            int w = matrix.GetLength(0); // width
            int h = matrix.GetLength(1); // height
    
            for (int x = 0; x < w; ++x)
            {
                for (int y = 0; y < h; ++y)
                {
                    if (matrix[x, y].Equals(value))
                        return Tuple.Create(x, y);
                }
            }
    
            return Tuple.Create(-1, -1);
        }
    }
    

    Then call below code:

    var coordinates = MyArray.CoordinatesOf((Object)sender);

    See if it helps.


    Kunal G

    Friday, December 27, 2013 12:24 PM

All replies

  • Have you tried simple loops, with right sizes?


    int found_i = -1;
    int found_j = -1;
    
    for(int i = 0; i < 100 && found_i < 0; ++i)
    {
        for(int j = 0; j < 200; ++j)
        {
            if( MyArray[i,j] == (object)sender) // (or maybe 'object.ReferenceEqual')
            {
                found_i = i;
                found_j = j;
                break;
            }
        }
    }



    • Edited by Viorel_MVP Thursday, December 26, 2013 9:27 PM
    Thursday, December 26, 2013 9:27 PM
  • Thankx.. and yes i have tried before with same loops but i was not using found_i variable thats why is was getting error index out of bound exception.. :)
    Friday, December 27, 2013 10:58 AM
  • Create a class with a method to find  index. Check this

    public static class ExtensionMethods
    {
        public static Tuple<int, int> CoordinatesOf<T>(this T[,] matrix, T value)
        {
            int w = matrix.GetLength(0); // width
            int h = matrix.GetLength(1); // height
    
            for (int x = 0; x < w; ++x)
            {
                for (int y = 0; y < h; ++y)
                {
                    if (matrix[x, y].Equals(value))
                        return Tuple.Create(x, y);
                }
            }
    
            return Tuple.Create(-1, -1);
        }
    }
    

    Then call below code:

    var coordinates = MyArray.CoordinatesOf((Object)sender);

    See if it helps.


    Kunal G

    Friday, December 27, 2013 12:24 PM