2011-10-13 98 views
0

我需要能够重新排列基于点击增加/减少箭头按钮的按钮数字列表。所以我有一个目前在SortedDoctionary项目列表。当我把它打印出来,它看起来是这样的:SortedDictionary项目键位置重新排序

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

当用户点击“UP”按钮,我想改变key[3]key[2]。所以换个位置吧。最终结果应该给我这样的输出:

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

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

+2

这听起来好像一个位置列表('名单'或'的LinkedList '等)将是一个更好的适合这里。 –

回答

0

假设你有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; 
    } 
} 
0
int index1 = 2; 
int index2 = 3; 

var temp = myDict[index1]; 
myDict[index1] = myDict[index2]; 
myDict[index2] = temp; 

这是传统的通过交换变温(以区分它与交换通过异或)。问题在哪里?

0

由于它是一个排序列表,想必您希望重点保持不变,但交换价值?

var lower = 2; 
var upper = 3; 

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