I have a Dictionary:
Dictionary<string, CustomClass> _details = new Dictionary<string, CustomClass>()
CustomClass implements IComparable as there is custom sort logic in the CompareTo() method.
I want to loop through all my CustomClass‘s in _details in a sorted order.
So I want to do something like this:
foreach (string value in _details.Values.Sort())
{
}
But Sort() isn’t a method on that type
What are my options here?
Your question is somewhat unclear, but on rereading it appears that you want to order by value rather than key. In that case, LINQ is the best approach with the
OrderBymethod:Or if you only want the values in the first place:
Note that you can’t sort a dictionary in-place –
Dictionary<,>is fundamentally unordered (or rather, the order is an implementation detail, and cannot be changed in a reliable manner).If you wanted to sort by key, it would probably be better to use
SortedList<,>orSortedDictionary<,>to start with. Both of these will keep the collection sorted by key permanently.