How to get the keys of a Dictionary<string, object> into a sorted string[]
What's the best way (*) to get the keys of a 开发者_开发技巧Dictionary<string, object>
into a string[]
(sorted alphabetically)?
Example:
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"]
(*) what I mean with "best way" is probably: it should be easy to write and read, but should still result in good performance
It depends what you mean by "best" - but I'd use:
string[] sortedKeys = d.Keys.OrderBy(x => x).ToArray();
Slightly more efficient but less fluent:
string[] sortedKeys = d.Keys.ToArray();
Array.Sort(sortedKeys);
精彩评论