获取 Dictionary<string, object>
的 key 的最佳方式 (*) 是什么?进入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"]
(*) 我所说的“最佳方式”可能是:它应该易于编写和阅读,但仍应产生良好的性能
最佳答案
这取决于你所说的“最好”是什么意思 - 但我会使用:
string[] sortedKeys = d.Keys.OrderBy(x => x).ToArray();
效率稍高,但不太流畅:
string[] sortedKeys = d.Keys.ToArray();
Array.Sort(sortedKeys);
关于generics - 如何将 Dictionary<string, object> 的键转换为已排序的 string[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4386313/