I'm looking for a better way to do the following.
using System;
using System.Collections;
Dictionary<int, string> namebyID = new Dictionary<int, string>();
Dictionary<string, int> idbyName = new Dictionary<string, int>();
Dictionary<string, string> valuebyName = new Dictionary<string, string>(); // users favorite dessert
/* Lets store information about "leethaxor" */
namebyID.Add(1234, "leethaxor");
idbyName.Add("leethaxor", 1234);
valuebyName.Add("leethaxor", "cake");
/* use case 1, I'm given an ID and i need the user's favorite dessert*/
if (namebyID.ContainsKey(1234))
{
string username;
namebyID.TryGetValue(1234, out username);
if (valuebyName.ContainsKey(username))
{
string dessert;
valuebyName.TryGetValue(username, out dessert);
Console.Write("ID 1234 has a username of " + username + " and loves " + dessert + "\n");
}
}
/* use case 2, I'm given a username and need to make sure they have a valid ID*/
if (idbyName.ContainsKey("leethaxor"))
{
int id;
idbyName.TryGetValue("leethaxor", out id);
Console.Write("username leethaxor has a valid ID of " + id + "\n");
}
I'd really like to not use 3 different dictionaries, as the id
, username
, and value
are all related to one another. Hashing key1(id)
and key2(username)
together won't work because I'm only given one or the other, not both.