I need to be able to reorder a list of numbers based on a button click of a increased/decreased arrow button. So I have a list of items currently in a SortedDoctionary
. When I print it out it looks like this:
key : value
1 : 1
2 : 2
3 : 25
4 : 29
5 : 31
When a user clicks the "UP" button I would like to change key[3]
to key[2]
. So just swap the position. The end results should give me an output like this:
key : value
1 : 1
2 : 25
3 : 2
4 : 29
5 : 31
So I need to switch开发者_开发百科 the position up or down in the list. Any help would be greatly appreciated!
Assuming you have Dictionary<int, int> dict
, try this:
private void Swap(int key)
{
int swap = dict[key];
dict[key] = dict[key + 1];
dict[key + 1] = swap;
}
or
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;
It's the classical swap-through-a-temp-variable (to distinguish it from the swap-through-xor). Where was the problem?
As it is a sorted list, presumably you want the Key to stay the same, but swap the value?
var lower = 2;
var upper = 3;
var tmp = collection[lower];
collection[lower] = collection[upper];
collection[upper] = tmp;
精彩评论