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:
How do I go about doing this?
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
}
See more on this question at Stackoverflow