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?
source
share