About Dictionary

Can I make sure that in dictionary in C# there will be only a single of a specific value in it?

For example, if I define a Dictionary which key is char and value is char, can I make sure that if the character 'a' is already an existing value, there won't be another value 'a' in the dictionary?

I have a solution, but I'd like to know if there's a better one:

static void Main()
{
    Dictionary<int, int> dic = new Dictionary<int, int>();
    bool valExists = false;
    Console.WriteLine("please enter key and value");
    int key = int.Parse(Console.ReadLine());
    int val = int.Parse(Console.ReadLine());
    foreach (KeyValuePair<int,int> keyval in dic)
    {
        if (keyval.Value == val)
        {
            valExists = true;
            break;
        }
    }
    if (!valExists)
        dic.Add(key, val);
}
Jon Skeet
people
quotationmark

Can I make sure that in dictionary in C# there will be only a single of a specific value in it?

Not as such (it wouldn't follow the the normal dictionary contract at that point), but it sounds like you effectively want a bi-directional dictionary. You can do that by composing two dictionaries, one going in each direction. I have an answer on another question with sample code for that.

That will allow you to go directly from "value" to "key" - if you have no need for that, you could always just keep a HashSet<TValue> as well as the normal TDictionary<TKey, TValue> and throw an exception if the caller tries to add a value which already exists.

Again, I would urge you not to do this by deriving from Dictionary<,> - instead just compose a Dictionary<,> and a HashSet<>. (I wouldn't even implement IDictionary<,>, as you have additional constraints which normal dictionaries don't include.)

people

See more on this question at Stackoverflow