我遇到需要对数组进行排序并保留当前键 - 值对的情况。
例如,这个数组:
(0) = 4
(1) = 3
(2) = 1
(3) = 2
需要像这样排序
(2) = 1
(3) = 2
(1) = 3
(0) = 4
保留原始密钥。 Array.Sort(myArray)按顺序排序,但不保留索引。我需要一个变体。
修改 使用链接,这似乎接近我想要的。我只需要删除额外的括号以将其转换为vb.net吗?
myList.Sort((firstPair,nextPair) =>
{
return firstPair.Value.CompareTo(nextPair.Value);
}
);
(我也会把它作为一个函数或其他东西整合?)
答案 0 :(得分:2)
在数组中,顺序由索引(您称之为“键”)决定。因此,不能有这样的数组:
(2) = 1
(3) = 2
(1) = 3
(0) = 4
您需要的是具有键,值和订单(独立于键)的数据结构。您可以使用List(Of KeyValuePair)
或(如果您使用.net 4)List(Of Tuple(Of Integer, Integer))
。 Ken在评论中提供的链接中显示了一些示例(为方便起见,我将在此重复):
编辑:另一种选择是使用LINQ自动创建排序的IEnumerable(Of Tuple(Of Integer, Integer))
:
Dim a() As Integer = {4, 3, 1, 2} ' This is your array
Dim tuples = a.Select(Function(value, key) New Tuple(Of Integer, Integer)(key, value))
Dim sorted = tuples.OrderBy(Function(t) t.Item2)
(未经测试,目前没有Visual Studio可用)
答案 1 :(得分:1)
由于您使用的是.net 2.0(因为您说过您在其中一条评论中使用了Visual Studio 2005),因此使用OrderedDictionary可能是您的选择,如果每个数组值只出现一次。由于OrderedDictionaries按键排序,您可以使用
将数组条目添加到此类字典中答案 2 :(得分:0)
您正在寻找的是将其存储为字典< int,int>并按字典排序。
我认为字典的VB .Net synatx是Dictionary(Int,Int)