Mathew Padley
Mathew Padley

Reputation: 102

C# Dictionary to Sorted JSON

I have a dictionary in the C# web project (MVC4) that I need to get via an AJAX Call and return a jSON. This part is all good, but the returned data is sorted by the key of the dictionary. I can't find a way of sorting by the value. The complication is the value is an object consisting of a string and an int. So the structure is

<key, <object>> 

where the object is a string, int

I can't change the structure of the dictionary as its used in other parts of the application on the page creation.

Any ideas of how I can accomplish this?

If not I'll rebuild the structure in the c# side of things.

Ta

Upvotes: 0

Views: 1259

Answers (1)

Cyril Gandon
Cyril Gandon

Reputation: 17058

Let's assume you have a class with an int and a string

public class MyObj 
{
    public int iValue { get; set; } 
    public string sValue { get; set; } 
}

You can sort a Dictionary by the value of the value:

var dictionary = new Dictionary<TKey, MyObj>();

var sortedKeyValuePair = dictionary.OrderBy(kvp => kvp.Value.iValue).ToList();

The result is a List < KeyValuePair < TKey, MyObj> > ordered by the int value of your object.

Upvotes: 4

Related Questions