C# iterating over Dictionary by arbitrary order

I have a Dictionary<string, List<Object>>. I loop through the keys of the dictionary and display the values grouped by the key. I know about SortedDictionary and OrderedDictionary but how do you sort a dictionary by a predefined order, not just alphabetically ascending/descending?

Assume that I know all possible keys in my dictionary will exist in the below list and want the dictionary to be sorted in the following order:

  1. Quick
  2. Brown
  3. Fox
  4. Jumped
  5. Over

How do I go about doing this?

Jon Skeet
people
quotationmark

You don't sort a Dictionary<,> at all. However, if you want to iterate over the entries (or keys) in a particular order, you can use LINQ's OrderBy - and to iterate a known set of values in that order, you can just have the ordered set somewhere else. For example:

string[] orderedKeys = { "Quick", "Brown", "Fox", "Jumped", "Over" };
var orderedPairs = dictionary.OrderBy(pair => orderedKeys.IndexOf(pair.Key));
foreach (var pair in orderedPairs)
{
    // Use pair.Key and pair.Value here
}

people

See more on this question at Stackoverflow