如何将Dictionary <string,object>的键放入已排序的字符串[]中

M4N*_*M4N 2 sorting generics dictionary c#-4.0

什么是得到一个按键的最佳方式(*)Dictionary<string, object>string[](按字母顺序排序)?

例:

var d = new Dictionary<string, int>();
d.Add("b", 1);
d.Add("f", 2);
d.Add("a", 3);

string[] sortedKeys = ...;
// sortedKeys should contain ["a", "b", "f"]
Run Code Online (Sandbox Code Playgroud)

(*)我对"最佳方式"的意思可能是:它应该易于编写和阅读,但仍应产生良好的性能

Jon*_*eet 5

这取决于你所说的"最好" - 但我会用:

string[] sortedKeys = d.Keys.OrderBy(x => x).ToArray();
Run Code Online (Sandbox Code Playgroud)

效率稍高但不太流利:

string[] sortedKeys = d.Keys.ToArray();
Array.Sort(sortedKeys);
Run Code Online (Sandbox Code Playgroud)