Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the .Net Dictionary look like it is sorted? [duplicate]

I was looking at some code my co-worker checked in, it looked like this:

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

I immediately told my co-worker that his code is wrong, because the Dictionary is a hash table, a non-sorted collection. He should either use an order-preserving collection, or sort the items later as he reads them from the dictionary with foreach, I said.

But he replied "No, no, my code is correct! Look: now that I have added the OrderBy, the items appear in correct order."

Turns out, on the test case, he was right. I tried on some other data, but it still was perfectly sorted!

I told him that he should not rely on this behaviour, but he disagrees, and I'm having trouble explaining why. Besides, I'm interested in why the order so often seem to be preserved.

So my question is... Why does the Dictionary, a fundamentally unsorted collection, looks so much like it is sorted?

like image 993
Eldritch Conundrum Avatar asked Mar 22 '12 13:03

Eldritch Conundrum


2 Answers

It is sorted, because of how Dictionary is implemented (and in your case items are added in order). But this is implementation details.

Tell your co-worker there is a SortedDictionary class that exists, this should convince him we can't rely on the items order with a simple Dictionary ;)

like image 146
ken2k Avatar answered Nov 02 '22 18:11

ken2k


When iterating over a dictionary you would get the items in it in the order they were inserted to the dictionary.

In the example, a list gets sorted, then each item gets added to the dictionary in turn.

The end result is that the items in the dictionary are in the sort order of the list.

However, this just happens to be the case with the current implementation of Dictionary - there is no guarantee that it will stay that way.

If you need to have the items in a Dictionary in a specific order, you should be using a SortedDictionary.

like image 45
Oded Avatar answered Nov 02 '22 17:11

Oded