Reputation: 9
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.
Upvotes: 0
Views: 76
Reputation: 88
Why not just use a class? Also, use TryGetValue() instead of ContainsKey(). What is more efficient: Dictionary TryGetValue or ContainsKey+Item?
public class User
{
public int Id;
public string Name;
public string Value;
}
Dictionary<int, User> userById = new Dictionary<int, User>();
Upvotes: 1
Reputation: 37113
You should definitly use your own class that holds all those information that belongs together. Relying on different dictionaries is a mess and gets really complex and complicated the more information you´r putting into those dictionaries.
So in your case you may create a class, let´s call it Person
. Every Person
has an Id
, a UserName
and a Value
:
class Person
{
public int Id { get; set; }
public string UserName { get; set; }
public string Value { get; set; }
}
Now create a list of those persons, e.g.:
var list = new List<Person> {
new Person { Id = 1234, UserName = "leethaxor", Value = "Cake" },
new Person { Id = 2, UserName = "Berta", Value = "AnotherValue" }
};
Now you can get the person
with a given Id
or a given UserName
:
var aPerson = list.FirstOrDefault(x => x.Id = 1234);
or
var aPerson = list.FirstOrDefault(x => x.UserName = "leethaxor");
You should definitly have a look on the basics of object-oriented programming, which is about objects and their behaviour.
Upvotes: 2