Is there a dictionary available in .NET
that could hold 2 keys and one value.
Like
Dictionary(Of TKey, Of TKey, TValue)
I have
At first I thought I could create a class that implmented IDictionary<TKey1, TValue>
and IDictionary<TKey2, TValue>
, and just have a single Dictionary as a field and delegate most methods to the single dictionary with minimal logic.
The problem with this approach is that TKey1
and TKey2
could be of the same type, which is a problem because this new class would be implementing the same interface twice. Which method should the runtime invoke when TKey1
is a string
and TKey2
is also a string
?
As others above have suggested, it is best to create your own data structure that utilizes one or two dictionaries behind the scenes. For example, if you knew ahead of time that you wanted to use a string
and an int
as your keys, you could use this approach:
public class StringIntDictionary<TValue> : IDictionary<string, TValue>, IDictionary<int, TValue>
{
private IDictionary<object, TValue> _dictionary = new Dictionary<object, TValue>();
// implement interface below, delegate to _dictionary
}
That would allow you to look use both string
and int
keys:
var dict = StringIntDictionary<bool>();
dict["abc"] = true;
dict[123] = true;
This is NOT a proper dictionary, but can be used for simple dictionary-like add remove functionalities.
This can be made generic as well, with proper implementation of IComparable in the keys types, and changing the dictionary code accordingly. (Note, default values of keys are not allowed to manage ambiguity!)
internal class KeyValueSet //this dictionary item is tailor made for this example
{
public string KeyStr { get; set; }
public int KeyInt { get; set; }
public int Value { get; set; }
public KeyValueSet() { }
public KeyValueSet(string keyStr, int keyInt, int value)
{
KeyStr = keyStr;
KeyInt = keyInt;
Value = value;
}
}
public class DoubleKeyDictionary
{
List<KeyValueSet> _list = new List<KeyValueSet>();
private void Add(KeyValueSet set)
{
if (set == null)
throw new InvalidOperationException("Cannot add null");
if (string.IsNullOrEmpty(set.KeyStr) && set.KeyInt == 0)
throw new InvalidOperationException("Invalid key");
if (!string.IsNullOrEmpty(set.KeyStr) && _list.Any(l => l.KeyStr.Equals(set.KeyStr))
|| set.KeyInt != 0 && _list.Any(l => l.KeyInt == set.KeyInt))
throw new InvalidOperationException("Either of keys exists");
_list.Add(set);
}
public void Add(string keyStr, int keyInt, int value)
{
Add(new KeyValueSet { KeyInt = keyInt, KeyStr = keyStr, Value = value });
}
public void Add(string key, int value)
{
Add(new KeyValueSet { KeyInt = 0, KeyStr = key, Value = value });
}
public void Add(int key, int value)
{
Add(new KeyValueSet { KeyInt = key, KeyStr = string.Empty, Value = value });
}
public void Remove(int key)
{
if (key == 0)
throw new InvalidDataException("Key not found");
var val = _list.First(l => l.KeyInt == key);
_list.Remove(val);
}
public void Remove(string key)
{
if (string.IsNullOrEmpty(key))
throw new InvalidDataException("Key not found");
var val = _list.First(l => l.KeyStr == key);
_list.Remove(val);
}
public void Remove(KeyValueSet item)
{
_list.Remove(item);
}
public int this[int index]
{
get
{
if (index != 0 && _list.Any(l => l.KeyInt == index))
return _list.First(l => l.KeyInt == index).Value;
throw new InvalidDataException("Key not found");
}
set
{
Add(index, value);
}
}
public int this[string key]
{
get
{
if (!string.IsNullOrEmpty(key) && _list.Any(l => l.KeyStr == key))
return _list.First(l => l.KeyStr == key).Value;
throw new InvalidDataException("Key not found");
}
set
{
Add(key, value);
}
}
}
Testing the DoubleKeyDictionary
var dict = new DoubleKeyDictionary();
dict.Add(123, 1);
dict.Add(234, 2);
dict.Add("k1", 3);
dict.Add("k2", 4);
dict[456] = 5;
dict["k3"] = 6;
dict.Add("k4", 567, 7);
dict.Remove(123);
Console.WriteLine(dict[234]); //2
Console.WriteLine(dict["k2"]); //4
Console.WriteLine(dict[456]); //5
Console.WriteLine(dict[567]); //7
Console.WriteLine(dict["k4"]); //7
Console.WriteLine(dict[123]); //exception
As you wish your value to be “findable” from either key, I would just use two dictionaries like you are doing now. However I would wrap this up in a class, with methods names like FindByXXX
and FindByYYY
.
The much harder question is how do you do a delete, as you need to know both keys at the time of the delete. Maybe your value stores both keys so you can pass the value into your delete method. Maybe you never need to remove items from the dictionaries. Or the code that needs to remove items knows both keys.
Hence there is no standard dictionary to do this, as the requirements are different between each user.
(Note you don’t want a dictionary with a composite key, as that would require you to know both keys whenever you wished to look up an item.)
As a local solution I use the easy approach:
Imagine I have a collection of products identified by a string and a form with buttons for each one of the products.
When managing the state of the buttons I need to find buttons by string key. When handling the clicks I need to find product IDs by button instance.
Instead of maintaining two separate dictionaries I do the following:
public class SPurchaseOption
{
public Button Button;
public string ProductID;
public string SomeOtherAssociatedData;
}
Dictionary<object, SPurchaseOption> purchaseOptions;
When the buttons are initialized I append two entries into the Dictionary
i.e.
Key: ProductID, Value: "SPurchaseOption"
Key: Button, Value: "SPurchaseOption"
For a more general approach and if you need a commonly used component you will have to build a wrap around two dictionaries i.e:
public class DoubleKeyedDictionary<TKey1, TKey2, TValue>
{
class SItem
{
public TKey1 key1;
public TKey2 key2;
public TValue value;
}
Dictionary<TKey1, SItem> dic1;
Dictionary<TKey2, SItem> dic2;
}
this will give access to both the value and alternative key by any of the keys.
Your solution has a big impact on the memory footprint of your application. As the dictionary grows it will take at least double the amount memory (for value types) required to store the actual data.
You could probably approach this from a different angle. Have two dictionaries :
var lookupDictionary = new Dictionary<string, string>();
var valuesDictionary = new Dictionary<string, [YourValueType]>();
From here on in its pretty simple.
// Add a new entry into the values dictionary and give it a unique key
valuesDictionary.Add("FooBar", "FUBAR VALUE");
// Add any number of lookup keys with the same value key
lookupDictionary.Add("Foo", "FooBar");
lookupDictionary.Add("Bar", "FooBar");
lookupDictionary.Add("Rab", "FooBar");
lookupDictionary.Add("Oof", "FooBar");
When you need to find something from valuesDictionary
you hit lookupDictionary
first. This will give you the key of the value you are looking for in the valuesDictionary
.
EDIT
I haven't addressed the deletion issue in my answer so here it goes :D
You would hit lookupDictionary
to find the value key and then delete all entries from lookupDictionary
that have that value.
Should be simple enough and safe since the valuesDictionary
is guaranteed to have a unique key hence you will not accidentally delete a lookup key for some other value.
However, as Ian Ringrose pointed out in a comment, you are going to do a full scan on the lookupDictionary
to delete. This may have an undesirable impact on performance in tight loops etc.
I can't really think of a good way to solve this issue at the moment. Perhaps someone else might have some ideas on how this could be improved.
I hope this helps.
If you are using C# 7.0 the best way to do this is to use tuple types and literals:
// Declare
var dict = new Dictionary<(string, long), long>();
// Add
dict.Add(("abc", 345), 111);
// Get
var searchedValue = dict[("abc", 345)];