I’ve a dictionary object:
Dictionary<string, string[]> dictCompanies = new Dictionary<string, string[]>();
How do sort this object on its key?
I tried using OrderBy like below, but it does no seem to work
dictCompanies .OrderByDescending(c=> c.Key);
I’m binding this dictionary object to a checkboxlist in aspx page.
I tried sorting this ListItemCollection using delegate…but still no luck…
Am i missing something here?
Thanks
You can’t sort an actual
Dictionary<TKey,TValue>– the order items come out of it is basically determined by the internal implementation. You might want to look atSortedDictionary<TKey,TValue>andSortedList<TKey,TValue>though – they still have key/value lookups, but allow you to sort based on the key. You can specify your ownIComparer<T>if you want to order by the keys in a particular way.Another option (depending on your situation) would be to stick with the dictionary right up until you need it – then copy it into a list and sort that before binding to the control. Obviously at that point you’d need to refresh the binding every time anything changed, but that may well not be a problem for you.
If your OrderBy statement was really on its own like that, by the way, you need to understand that LINQ operators always operators always take a sequence and return a different sequence (or an aggregate result) – they never modify the sequence in-place. Indeed, they can’t as
IEnumerable<T>is a read-only interface.