mtoy
mtoy

Reputation: 195

sort nested Dictionary

I would like to sort Dictionary by value in nested Dictionary.

Dictionary<int, Dictionary<string, string>> Data = new Dictionary<int, Dictionary<string, string>>();

Dictionary<string, string> oneRow = new Dictionary<string,string>();
oneRow.Add("id", "1");
oneRow.Add("name", "John");
oneRow.Add("surname", "Petrucci");
oneRow.Add("data", "2014-01-01");
oneRow.Add("active", "1");
this.Data[1] = oneRow;

oneRow = new Dictionary<string, string>();
oneRow.Add("id", "2");
oneRow.Add("name", "Joe");
oneRow.Add("surname", "Satriani");
oneRow.Add("data", "2014-02-02");
oneRow.Add("active", "1");
this.Data[2] = oneRow;

oneRow = new Dictionary<string, string>();
oneRow.Add("id", "3");
oneRow.Add("name", "Steve");
oneRow.Add("surname", "Vai");
oneRow.Add("data", "2014-03-03");
oneRow.Add("active", "0");
this.Data[3] = oneRow;

How can I sort this.Data by 'name' or for example by 'surname' DESC ?

I was searching but I have not found solution.

Upvotes: 1

Views: 1431

Answers (1)

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

Here is the shortest way:

Data = Data.OrderByDescending(x => x.Value["name"])
           .ToDictionary(x => x.Key, x => x.Value);

Upvotes: 1

Related Questions