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?