// initialize the array and the indexes array
var a2D = new int[2][];
a2D[0] = new[] { 3, 14, 15, 92, 65, 35 }; // <-- your array (fake data here)
a2D[1] = Enumerable.Range(0, a2D[0].Length).ToArray(); // create the indexes row
// sort the first row and the second one containing the indexes
Array.Sort(a2D[0], a2D[1]);
// now a2D array contains:
// row 0: 3, 14, 15, 35, 65, 92
// row 1: 0, 1, 2, 5, 4, 3
// and you can perform binary search on the first row:
int columnIndexOf35 = Array.BinarySearch(a2D[0], 35);
// columnIndexOf35 = 3
//
// a2D[0][columnIndexOf35] = 35 <- value
// a2D[1][columnIndexOf35] = 5 <- original index
class IndexedData:IComparable
{
public MyType Data;
public int OriginalIndex;
public int CompareTo(object obj) {
// add correct checks for null,.. here
// and return correct comparison result.
// I.e. if MyType is IComparable - just delegate.
return Data.CompareTo(obj);
}
var unsortedStartingArray = new[] {3, 6, 2, 1, 20, 20};
var q = unsortedStartingArray
.Select((item, index) => new {item, index})
.ToLookup(x => x.item, x => x.index);
var notFound = q[30]; // An empty array. Nothing found
var indexOf1 = q[1].First(); // returns 3
var multipleIndexsOf20 = q[20]; // Returns an array with 4, 5
4 回答
好吧,如果我理解正确,你需要这样的东西:
根据MSDN,
Array.BinarySearch
方法仅对一维数组进行操作,因此在您的情况下不可能直接使用它 . 您拥有的一些选项是:将第一列提取到单独的数组中并在其上调用
Array.BinarySearch
.定义实现接口
IComparable
的自定义类Pair,并使用此类的实例构造数组 .自己在二维数组上实现二进制搜索 .
看起来你想拥有保存数据和“原始索引”的对象,而不是按数据排序/搜索对象数组 .
(这个答案显示了安德烈的选择2)
检查MSDN上的IComparable以获取实施/使用详细信息 .
根据您之后计划对阵列执行的操作,另一种解决方案可能是使用LINQ .
然后,查找的索引将是您要搜索的值 . 性能方面,我认为这比我的原油测试速度要快5倍 .