0

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?

4
  • How would one add/remove work? A params[] overload? In my mind you still have to call dict.Add() multiple times, which means @Verarind's solution is the best option. Commented Oct 5, 2015 at 17:19
  • Yeah, I actually already considered the multiple keys/multiple Dictionaries solutions, but I have to support over 50 languages! Either way, that means 50 copies of a single person, and I do a lot of adding/removing. It's kind of a waste of space. Wondering if there was a more elegant solution to this. Commented Oct 5, 2015 at 17:31
  • 1
    @user3685285 waste of space? You need to store a key to a pointer. I don't think that there is a structure that needs less space than a dictionary and supports a fast way to access the values. Commented Oct 5, 2015 at 17:40
  • @Vera rind, I agree that a Dictionary is the best structure for 1 to many mappings, but I need a many to 1 mapping. Was hoping there'd be a more elegant solution, but it seems I can't get there without building a custom structure with pointers. Commented Oct 7, 2015 at 14:22

1 Answer 1

2

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...

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.