SortedDictionary项关键字位置重新排序

本文关键字:排序 新排序 关键字 位置 SortedDictionary | 更新日期: 2023-09-27 18:11:14

我需要能够根据增加/减少箭头按钮的按钮点击来重新排序数字列表。所以我有一个SortedDoctionary中当前项目的列表。当我打印出来时,它看起来像这样:

key : value    
 1  :  1
 2  :  2
 3  :  25
 4  :  29
 5  :  31

当用户单击"向上"按钮时,我想将key[3]更改为key[2]。所以换个位置就行了。最终结果应该会给我一个这样的输出:

key : value
 1  :  1
 2  :  25
 3  :  2
 4  :  29
 5  :  31

所以我需要在列表中向上或向下切换位置。如有任何帮助,我们将不胜感激!

SortedDictionary项关键字位置重新排序

假设您有Dictionary<int, int> dict,请尝试以下操作:

private void Swap(int key)
{
    int swap = dict[key];
    dict[key] = dict[key + 1];
    dict[key + 1] = swap;
}

private void Swap(int key1, int key2)
{
    if (key1 != key2)
    {
        int swap = dict[key1];
        dict[key1] = dict[key2];
        dict[key2] = swap;
    }
}
int index1 = 2;
int index2 = 3;
var temp = myDict[index1];
myDict[index1] = myDict[index2];
myDict[index2] = temp;

这是经典的通过时间变量的交换(将其与通过xor的交换区分开来(。问题出在哪里?

由于它是一个排序列表,您可能希望Key保持不变,但交换值?

var lower = 2;
var upper = 3;
var tmp = collection[lower];
collection[lower] = collection[upper];
collection[upper] = tmp;