如何切换字典中所有值的顺序并颠倒顺序?

时间:2018-10-19 08:42:11

标签: c# dictionary key key-value

我没有完成...

我有代码:

TypeError: e.getFile is not a function

我应该使用Console.Writeline输出:

Dictionary<string, string>[] dic = new Dictionary<string, string>[2];
dic[0].Add("10", "a");
dic[1].Add("20", "b");

这意味着我首先应该更改值,然后更改键,但是我不知道如何管理它。我尝试了Microsoft的官方网站,但我没有再继续。

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

您的代码无法编译

但是也许您想要这样的东西

Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("10", "a");
dic.Add("20", "b");

// Ouput
foreach (var key in dic.Keys)
   Console.WriteLine(key + " "+ dic[key]);

// Change 
dic["10"] = "C";
dic["20"] = "D";

// Ouput    
foreach (var key in dic.Keys)
   Console.WriteLine(key + " " + dic[key]);

或者也许您只想要一个列表

var list = new List<(string,string)>();
list.Add(("10", "a"));
list.Add(("20", "b"));

// order one way
foreach (var item in list.OrderBy(x => x.Item1))
   Console.WriteLine(item);

// order another
foreach (var item in list.OrderByDescending(x => x.Item1))
   Console.WriteLine(item);

输出

10 a
20 b
10 C
20 D
(10, a)
(20, b)
(20, b)
(10, a)

Full Demo Here

答案 1 :(得分:0)

首先我应该说这个要求不应该用字典来解决,因为它不是有序集合。这意味着您不应该依赖于键的字典顺序,因为如果添加或删除对,则键的顺序可能会更改,并且在.NET的下一版本中可能会更改。

但是,如果这仅仅是一种练习。您可以使用List<T>通过索引访问它:

Dictionary<string, string> dict = new Dictionary<string, string>() {{"10", "a"}, {"20", "b"}};

List<KeyValuePair<string, string>> listDict = dict.ToList();
// 1.) switch the values, last becomes first and vice-versa
for (int i = 0; i < listDict.Count; i++)
{
    string oppositeValue = listDict[listDict.Count - 1 - i].Value;
    dict[listDict[i].Key] = oppositeValue;
}
// 2.) reverse the dictionary to "switch" the keys, this is not recommended with a dictionary, because it is not an ordered collection
dict = dict.Reverse().ToDictionary(kv => kv.Key, kv => kv.Value);