I am looking for a C# container that can map multiple keys to a single object. For example: a single person can be referenced by his English name, or his Spanish name. I want to do this so that I don't have to create multiple copies of Dictionaries, and when I add/remove from the structure, I only have to add/remove once. Does such a structure exist?
1 Answer
Yes it exists: Dictionary<TKey, TValue>
There is no reason why you can't add a single object instance with multiple keys:
public class Person
{
public string EnglishName { get; set; }
public string SpanishName { get; set; }
}
public static class PersonDictExtensions
{
public static void AddPerson(this IDictionary<string, Person> persons, Person person)
{
persons.Add(person.EnglishName, person);
persons.Add(person.SpanishName, person);
}
public static void RemovePerson(this IDictionary<string, Person> persons, Person person)
{
foreach (var item in persons.Where(x => object.ReferenceEquals(x.Value, person)).ToList())
{
persons.Remove(item.Key);
}
}
}
var person = new Person { EnglishName = "Foo", SpanishName = "Bar" };
var dict = new Dictionary<string, Person>();
dict.AddPerson(person);
dict.RemovePerson(person);
EDIT Ups I understand: only one add and remove? Hm. Doesn't know that such a structure exists. Maybe you can add an extension method to handle that cases.
I changed the code...
params[]overload? In my mind you still have to calldict.Add()multiple times, which means @Verarind's solution is the best option.