Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Short example of how to use .NET Dictionaries.
// Create new dictionary.
Dictionary<Player, int> highscores = new Dictionary<Player, int>();
// Add some players.
var playerNick = new Player { Name = "Nick", Id = 1 };
var playerChristian = new Player { Name = "Christian", Id = 2 };
highscores.Add(playerNick, 33);
highscores.Add(playerChristian, 45);
// Print player count.
Console.WriteLine("There are {0} players with scores:", highscores.Count);
// Show all scores.
foreach (var nameWithScore in highscores)
{
Console.WriteLine("{0}: {1}", nameWithScore.Key, nameWithScore.Value);
}
// Get specific value.
Console.WriteLine("Nick has a score of {0}.", highscores[playerNick]);
// Safe way to get specific value.
int score;
if (highscores.TryGetValue(playerChristian, out score))
{
Console.WriteLine("Christian has a score of {0}.", score);
}
// Wait for key.
Console.ReadLine();
public class Player
{
#region Properties
public int Id { get; set; }
public string Name { get; set; }
#endregion
#region Public Methods and Operators
public override string ToString()
{
return this.Name;
}
#endregion
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment