Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi-key dictionaries (of another kind) in C#?

Building on this question, is there a simple solution for having a multi-key dictionary where either key individually can be used to identify the value?

ie.

MultikeyDictionary<TKey1, TKey2, TValue> foo;
foo.Add(key1, key2, value);
myValue = foo[key1];
// value == myValue
foo.Remove(key2);
myValue = foo[key1]; // invalid, Exception or null returned
like image 926
Matthew Scharley Avatar asked Jul 23 '09 13:07

Matthew Scharley


People also ask

Can dictionary values have different types?

By contrast, there are no restrictions on dictionary values. Literally none at all. A dictionary value can be any type of object Python supports, including mutable types like lists and dictionaries, and user-defined objects, which you will learn about in upcoming tutorials.

What is a Multivalue dictionary?

adjective. having many values, meanings, or appeals. synonyms: multivalent ambiguous. having more than one possible meaning.

Can a dictionary have duplicate keys C?

In Dictionary, key must be unique. Duplicate keys are not allowed if you try to use duplicate key then compiler will throw an exception. In Dictionary, you can only store same types of elements. The capacity of a Dictionary is the number of elements that Dictionary can hold.

Can dictionaries have two keys?

No, each key in a dictionary should be unique. You can't have two keys with the same value. Attempting to use the same key again will just overwrite the previous value stored. If a key needs to store multiple values, then the value associated with the key should be a list or another dictionary.


1 Answers

This blog post seems to detail a rather decent implementation.

Multi-key generic dictionary class for C#

MultiKeyDictionary is a C# class that wraps and extends the Generic Dictionary object provided by Microsoft in .NET 2.0 and above. This allows a developer to create a generic dictionary of values and reference the value list through two keys instead of just the one provided by the Microsoft implementation of the Generic Dictionary<...>. You can see my article on CodeProject (here), however this code is more up-to-date and bug free.

like image 72
Noldorin Avatar answered Nov 15 '22 19:11

Noldorin