Take the 2-minute tour ×

What's the best way (*) to get the keys of a Dictionary<string, object> into a string[] (sorted alphabetically)?


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

share|improve this question

1 Answer 1

up vote 5 down vote accepted

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();
share|improve this answer
Thanks a lot! I was struggling with the OrderBy() method –  M4N Dec 8 '10 at 10:19
There's also the more LINQy syntax: (from k in d.Keys orderby k select k).ToArray() if you have trouble with OrderBy(). –  Gabe Dec 9 '10 at 8:08
@Gabe: True - although I would advise people to learn both forms... here the query expression is only adding noise compared with the extension method form, IMO. –  Jon Skeet Dec 9 '10 at 8:19

Your Answer


