如何搜索一个多维数组? [英] How do I search a multi-dimensional array?
问题描述
在C#中,
Array.Find<T>(arrayName, value);
搜索一维阵列。反正是有一个多维数组做到这一点(例如 myArray的[,,]
)?
推荐答案
使用Excel和VSTO工作,我处理多维数组的所有时间。有像Array.Find)多维数组(没有内置功能。
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().
您基本上有两种选择:创建您自己的helper方法和实施通用搜索模式出现,或产生域对象关联到多维数组的内容列表。我个人倾向于选择后者。
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);
这篇关于如何搜索一个多维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!