【问题标题】:How to switch order of all values in a dictionary and reverse the order it?如何切换字典中所有值的顺序并反转顺序?
【发布时间】:2018-10-19 08:42:11
【问题描述】:

我没有完成它......

我有代码:

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

我应该用 Console.Writeline 输出:

10, b 
20, a

20, a
10, b

这意味着我应该首先更改值,然后更改密钥,但我不明白如何管理它。我尝试了微软的官方网站,但我没有进一步。

谁能帮帮我?

【问题讨论】:

  • 你好,你能分享更多你的代码吗?您尝试过什么,目前没有什么解决方案?
  • 看来您滥用字典是为了别的。这是真正的需求还是只是一种体验?特别是第二个我不明白,因为它们的键值对不会改变,只是顺序。但是字典没有顺序,至少你不应该依赖它。
  • 我也有点困惑,但我从我工作的地方得到了练习。还有一个练习,字典的定义类似于 Dictionary ,最后我应该输出: d, 1 尽管键是整数。这太他妈困惑了。因此,我在这里寻求有关令人困惑的练习的帮助
  • 您似乎也将字典与字典数组混淆了。您正在使用一个数组,但我认为您只需要一个。至少向我们提供字典的编译版本,这根本不是有效的语法:new Dictionary&lt;string, string[2]
  • @Tim Schmelter 哦,我忘了 ">"

标签: c# dictionary key key-value


【解决方案1】:

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

但是,如果这只是一个练习。您可以使用List&lt;T&gt; 按索引访问它:

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);

【讨论】:

  • 非常感谢。我永远不会想出这样的主意。这就是我问的原因。哦,我知道我的代码语法错误。我一直想到一个列表而不是字典,因为使用列表更容易解决这个问题。
  • @G.Don:是的,这就是为什么我提到字典不是有序集合的原因,并且它不允许通过索引访问键或值是有充分理由的。即使您可以枚举它,该顺序也可能不稳定。您需要从中创建一个列表(或数组),以便能够按索引访问每个键值。这就是我上面对dict.Tolist所做的。
  • 是的,我现在明白了,或者说明白你做了什么!非常感谢。
【解决方案2】:

你的代码不会编译

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-13
    • 2021-11-17
    相关资源
    最近更新 更多