How do I search a multi-dimensional array?

允我心安 提交于 2020-01-02 05:44:13

问题


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[,,])?


回答1:


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);



回答2:


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




回答3:


Flatten the multidimensional array and then use Array.Find.



来源:https://stackoverflow.com/questions/6084940/how-do-i-search-a-multi-dimensional-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!