在C#Dictionary中交换两个键/值对

Bug*_*pen 0 c# swap dictionary key-value

这就是我想要做的.

有一个包含54个键/值对象的Dictionary.我希望索引i处的键/值对与索引j处的键/值对交换...

int i=1; int j=3;
Dictionary<String, int> theDeck = new Dictionary<String, int>();
theDeck.Add("zero",  0);
theDeck.Add("one",   1);
theDeck.Add("two",   2);
theDeck.Add("three", 3);
KeyValuePair<String, int> p1 = theDeck.ElementAt(i);
KeyValuePair<String, int> p2 = theDeck.ElementAt(j);
theDeck.ElementAt(i) = p2; //THIS LINE DOES NOT WORK. WHAT IS ITS ALTERNATIVE
theDeck.ElementAt(j) = p1; //THIS LINE DOES NOT WORK. WHAT IS ITS ALTERNATIVE
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 6

Dictionary<,>实例不具有 "指标" -你不应该把他们当作在所有订购.在迭代条目时您可能会注意到的任何顺序都应被视为实现细节.

如果您需要特定订单,可以使用各种不同类型,具体取决于您的要求.例如,排序根据你使用的键SortedDictionary<,>SortedList<,>.对于任意排序,请考虑OrderedDictionary(遗憾的是非泛型).

你肯定需要一本字典吗?你可以只使用一个List<KeyValuePair<string, int>>或者一个List<Card>地方Card是一个自定义类型?(我猜测你的用例 - Card可以是代表你输入内容的任何类型.)