6

I am working in MVC. It is an $.AJAX post and I am returning a Dictionary which is already sorted descending by the key. I then pass this dictionary as JSON Result.

But in the browser, what I am getting is the same dictionary but sorted ascending by the key.

Is there any reason why it is getting sorted the other way or If this is any issue please let me know what should I do to get the dictionary with same sorted order.

I have googled already and I didn't find anything related to this.

Regards, Venkatesan R

tereško
  • 56,151
  • 24
  • 92
  • 147
Venkatesan Rethinam
  • 143
  • 1
  • 3
  • 15

1 Answers1

5

Dictionary is not ordered. This is okay, because JSON objects (and the corresponding JavaScript objects) are also unordered1 maps of key/value pairs.

Instead, use a JSON array (e.g. mapped to List) to maintain an ordered sequence.


1 It is unfortunate that the returned data (or perhaps display of) appear sorted in a particular order as there is no such guarantee.

See also:

Community
  • 1
  • 1
user2864740
  • 54,112
  • 10
  • 112
  • 187
  • 2
    It might not be coincidence, but in any case it is not guaranteed, so you shouldn't assume that it will be sorted ascending. – Tim S. Nov 06 '13 at 21:49