Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I search a multi-dimensional array?

In C#,

Array.Find<T>(arrayName, value);

searches a one dimensional array. Is there anyway to do this for a multidimensional array (e.g. myArray[,,])?

like image 793
Joel Avatar asked Dec 28 '22 20:12

Joel


2 Answers

Working with Excel and VSTO, I deal with multidimensional arrays all the time. There are no built-in functions for multidimensional array like Array.Find().

You basically have two choices: create your own helper methods and implement a generic search pattern there, or generate a list of domain objects correlating to the contents of the multidimensional array. I personally have tended to choose the latter option.

If you choose to write a helper method, it could look something (very roughly) like this:

// you could easily modify this code to handle 3D arrays, etc.
public static class ArrayHelper
{
    public static object FindInDimensions(this object[,] target, 
      object searchTerm)
    {
        object result = null;
        var rowLowerLimit = target.GetLowerBound(0);
        var rowUpperLimit = target.GetUpperBound(0);

        var colLowerLimit = target.GetLowerBound(1);
        var colUpperLimit = target.GetUpperBound(1);

        for (int row = rowLowerLimit; row < rowUpperLimit; row++)
        {
            for (int col = colLowerLimit; col < colUpperLimit; col++)
            {
                // you could do the search here...
            }
        }

        return result;
    }
}

You would refer to the static extension like this in other parts of your application code:

object[,] myArray = GetMyArray(); // gets an array[,]
myArray.FindInDimensions(someObject);
like image 164
code4life Avatar answered Jan 07 '23 12:01

code4life


There is no built in multi-dimensional search function. You'd have to write it yourself.

like image 36
blueberryfields Avatar answered Jan 07 '23 11:01

blueberryfields