【问题标题】:SortedDictionary item key position reorderingSortedDictionary 项关键位置重新排序
【发布时间】:2011-10-13 13:12:46
【问题描述】:

我需要能够根据单击增加/减少箭头按钮的按钮重新排序数字列表。所以我有一个当前在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

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

【问题讨论】:

  • 在我看来,位置列表(List<T>LinkedList<T> 等)更适合这里。

标签: c# asp.net dictionary position


【解决方案1】:

假设你有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;
    }
}

【讨论】:

    【解决方案2】:
    int index1 = 2;
    int index2 = 3;
    
    var temp = myDict[index1];
    myDict[index1] = myDict[index2];
    myDict[index2] = temp;
    

    这是经典的swap-through-a-temp-variable(以区别于swap-through-xor)。问题出在哪里?

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 2012-10-30
        • 1970-01-01
        • 1970-01-01
        • 2011-02-06
        • 1970-01-01
        • 2010-10-18
        相关资源
        最近更新 更多