Why does the .Net dictionary look like it's sorted?

I looked at the code that my colleague checked, it looked like this:

return list.OrderBy(item => item.Order).ToDictionary(item => item.Id);

I immediately told my employee that his code is incorrect, because it Dictionaryis a hash table, not a sorted collection. He should either use a collection that stores the order, or sort the items later when he reads them from the dictionary using foreach, I said.

But he replied: "No, no, my code is correct! Look: now, when I added OrderBy, the elements are displayed in the correct order."

It turns out that in the test case he was right. I tried some other data, but it was still perfectly sorted!

I told him that he should not rely on this behavior, but he did not agree, and I had problems explaining the reasons. Also, I am wondering why the order is kept so often.

So my question is ... Why Dictionarydoes a collection that is fundamentally unsorted look like it is sorting?

+5
source share
2 answers

It is sorted, due to how it is implemented Dictionary(and in your case the elements are added in order). But these are implementation details .

Tell your colleague that there is a SortedDictionary class that should convince him that we cannot rely on the order of things with a simple one Dictionary;)

+6
source

, .

, .

, .

Dictionary - , .

Dictionary , SortedDictionary.

+3

All Articles