Dictionary sorting

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
					
public class Program
{
	public static void Main()
	{
		 IDictionary<string, object> userDict = new Dictionary<string, object>();
		IDictionary<string, object> user1 = new Dictionary<string, object>();
		IDictionary<string, object> user2 = new Dictionary<string, object>();
		
		const string scoreKey = "score";
		const string nameKey = "name";
		
		user1.Add(nameKey, "John");
		user1.Add(scoreKey, 5);
		
		user2.Add(nameKey, "Pete");
		user2.Add(scoreKey, 10);
		
		
		userDict.Add("<userid1>", user1);
		userDict.Add("<userid2>", user2);
		
		var highscores = userDict
			.OrderByDescending(u => ((IDictionary<string, object>)u.Value)[scoreKey])
			.Select(u => new {
				    Name = ((IDictionary<string, object>)u.Value)[nameKey], 
			        Score = ((IDictionary<string, object>)u.Value)[scoreKey]
			    }
			 );
 		
		foreach(var score in highscores) {
			Console.WriteLine("Name: " + score.Name + " , Score: " + score.Score);
		}
		
	}
}
;