Sorting dictionary alphabetically I have this method which successfully sorts the incoming dictionary alphabetically:

private Dictionary&lt;string, string&gt; sortMacroDictionary(Dictionary&lt;string, string&gt; whichDictionary) {
    Dictionary&lt;string, string&gt; sortedDictionary = new Dictionary&lt;string, string&gt;();
    List&lt;string&gt; tempList = new List&lt;string&gt;();
    string outValue;

    if (whichDictionary.Count &gt; 0) {
        foreach (var entry in whichDictionary) {
            tempList.Add(entry.Key);
        }

        tempList.Sort();

        foreach (string entry in tempList) {
            if (whichDictionary.TryGetValue(entry, out outValue)) {
                sortedDictionary.Add(entry, outValue);
            }
        }
    }

    return sortedDictionary;
}


It works as intended and I am not experiencing any issues with it. I'm just wondering if there is a way to improve this method? Maybe there are some issues with my current code that I haven't foreseen?
I'm afraid your sorting is in vain because the normal dictionary does not guarantee that the items will be enumerated in the same order as you added them:


  For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair&lt;TKey, TValue&gt; structure representing a value and its key. The order in which the items are returned is undefined.


If they are, then this is a pure coincidence. 

You'll be safe if you use the SortedDictionary instead which:


  Represents a collection of key/value pairs that are sorted on the key.




If we assume for a moment that a Dictionary&lt;TKey, TValue&gt; can be sorted the way you do it then it can be also achieved with a simple LINQ query:

private Dictionary&lt;string, string&gt; sortMacroDictionary(Dictionary&lt;string, string&gt; source)
{
    return source.Keys.OrderBy(k =&gt; k).ToDictionary(k =&gt; k, k =&gt; source[k]);    
}


You first get all keys, order them, then you create a new dictionary based on the new key order. This is virtually the same as what you are doing now but much shorter.

As far as your code is concerned there is no need to check whichDictionary.Count &gt; 0 becasue if the dictionary is empty your loops won't run. The same applies to this query.

My advice is to use the SortedDictionary. This dictionary maintains the order the entire time. It sorts itself so to speak, as you add/remove items. You don't have to sort it manually.