Related
I am trying to create a recursive method that makes a deep copy of a dictionary to any length by checking if the hash value is another dictionary and then copy it again before hashing it.
I have tried this and the compiler rejects the line in Blockquote, who can find the error?
private Dictionary<TKey, TValue> NestedCopy<TKey, TValue>(Dictionary<TKey,
TValue> nestedDict)
{
var retDict = new Dictionary<TKey, TValue>();
foreach (var dict in nestedDict)
{
if (dict.Value is Dictionary<Object, Object>)
{
retDict[dict.Key] = NestedCopy(dict.Value asDictionary<object, object>);
}
}
return retDict;
}
retDict[dict.Key] = NestedCopy(dict.Value asDictionary);
This is the error line,
It says it cannot implicitly convert from Dictionary to TValue
Dictionary<string, Dictionary<string, int>> dict;
var newDict = NestedCopy(newDict);
//I expect newDict to be a copy of dict
There is no way for the compiler to statically infer the recursive call. So, you gonna need reflection or at least let the compiler do the reflection for you by using the dynamic keyword:
private Dictionary<TKey, TValue> NestedCopy<TKey, TValue>(
Dictionary<TKey, TValue> nestedDict)
{
var retDict = new Dictionary<TKey, TValue>();
foreach (var dict in nestedDict)
{
if (typeof(TValue).IsGenericType && typeof(TValue).GetGenericTypeDefinition() == typeof(Dictionary<,>))
{
retDict[dict.Key] = (TValue)NestedCopy((dynamic)dict.Value);
}
else
{
retDict[dict.Key] = dict.Value;
}
}
return retDict;
}
The more explicit code with hand-made reflection could look as follows:
private static Dictionary<TKey, TValue> NestedCopy<TKey, TValue>(
Dictionary<TKey, TValue> nestedDict)
{
var reflectionMethod = typeof(Program).GetMethod("NestedCopy", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
var retDict = new Dictionary<TKey, TValue>();
foreach (var dict in nestedDict)
{
if (typeof(TValue).IsGenericType && typeof(TValue).GetGenericTypeDefinition() == typeof(Dictionary<,>))
{
var methodToCall = reflectionMethod.MakeGenericMethod(typeof(TValue).GetGenericArguments());
retDict[dict.Key] = (TValue)methodToCall.Invoke(null, new object[] { dict.Value });
}
else
{
retDict[dict.Key] = dict.Value;
}
}
return retDict;
}
Note this assumes the method to belong to Program class and I made it static since its not using any context.
Since the decision for the if-else doesn't depend on dict.Value but only on the TValue that stays the same throughout the method, you could also move the condition out of the loop:
private static Dictionary<TKey, TValue> NestedCopy<TKey, TValue>(
Dictionary<TKey, TValue> nestedDict)
{
var retDict = new Dictionary<TKey, TValue>();
Func<TValue, TValue> clone;
if (typeof(TValue).IsGenericType && typeof(TValue).GetGenericTypeDefinition() == typeof(Dictionary<,>))
{
clone = v => NestedCopy((dynamic)v);
}
else
{
clone = v => v;
}
foreach (var dict in nestedDict)
{
retDict[dict.Key] = clone(dict.Value);
}
return retDict;
}
I think you don't need to recursive it, it relies on you how to implement the TValue.Clone method.
private Dictionary<TKey, TValue> CloneDictionary<TKey, TValue>(Dictionary<TKey, TValue> sourceDic)
where TValue : ICloneable
{
var ret = new Dictionary<TKey, TValue>(sourceDic.Count, sourceDic.Comparer);
foreach (KeyValuePair<TKey, TValue> entry in sourceDic)
{
ret.Add(entry.Key, (TValue)entry.Value.Clone());
}
return ret;
}
Essentially, I want a data structure that resembles Dictionary, but having a difference that its values are also unique. In another words, it depicts a one to one relationship rather than one to many.
An example should explain better. Suppose I call this new data structure MyMapping, and I want to save names of married couples in it:
MyMapping<string, string> myMapping = new MyMapping<string, string>();
myMapping.Add("Joe", "Ann");
myMapping.Add("Ann", "Joe");// not allowed
myMapping.Add("Joe", "Mary");// not allowed
myMapping.Add("William", "Katie");// ok
string partner = myMapping["Ann"];// result is Joe
partner = myMapping["Joe"];//result is Ann
what you're looking for is also called a Two-way dictionary. Take a look at other SO answers to the same question.
I started building a TwoWayDictionary for you based on IDictionary
http://msdn.microsoft.com/en-us/library/s4ys34ea.aspx
//only one generic parameter needed, as key and value have same type.
public class TwoWayDictionary<TKey> : IDictionary<TKey, TKey>
{
private Dictionary<TKey, TKey> _primary;
private Dictionary<TKey, TKey> _secondary;
public TwoWayDictionary()
{
_primary = new Dictionary<TKey, TKey>();
_secondary = new Dictionary<TKey, TKey>();
}
public int Count {get{return _primary.Count;}}
public bool IsReadOnly {get{return _primary.IsReadOnly;}}
public TKey this[TKey key]
{
get
{
return this.GetValue(key);
}
set
{
this.Add(key, value);
}
}
public ICollection<TKey> Keys {get {return _primary.Keys;}}
public ICollection<TKey> Values {get {return _primary.Values;}}
private TKey GetValue(TKey key)
{
if (_primary.ContainsKey(key))
{
return _primary[key];
}
if (_secondary.ContainsKey(key))
{
return _secondary[key];
}
throw new KeyNotFoundException("key is not found");
}
public void Add(KeyValuePair<TKey, TKey> item)
{
this.Add(item.Key, item.Value);
}
public void Add(TKey key, TKey value)
{
if (key == null || value == null)
{
throw new ArguementNullException("key or value is null");
}
if (_primary.ContainsKey(key) || _secondary.ContainsKey(key)
|| _primary.ContainsKey(value) || _secondary.ContainsKey(value))
{
throw new ArgumentException("Item with same key or value already exists");
}
_primary.Add(key, value);
_secondary.Add(value, key);
}
public void Clear()
{
_primary.Clear();
_secondary.Clear();
}
public void Contains(KeyValuePair<TKey, TKey> item)
{
return _primary.Contains(item) || _secondary.Contains(item);
}
public void ContainsKey(TKey key)
{
return _primary.ContainsKey(key) || _secondary.ContainsKey(key);
}
public void CopyTo(KeyValuePair<TKey, TKey>[] array, int arrayIndex)
{
return _primary.CopyTo(array, arrayIndex);
}
... TODO finish implementing IDictionary
Two dictionaries are not necessary - a dictionary with a HashSet will suffice. The HashSet will of course hold and guard the values.
EDIT: additional explanation regarding question in the comment
The new collection would consist of an instance of a Dictionary and a HashSet, like this:
class UniqueValueDictionary<TKey, TValue>
{
//...
private Dictionary<TKey, TValue> dictionary;
private HashSet<TValue> valueSet;
}
When inserting to the dictionary you verify if the value already exists:
public void Add(TKey key, TValue value)
{
if (valueSet.Contains(value))
{
//throw appropriate exception
}
dictionary.Add(key, value);
valueSet.Add(value);
}
When removing:
public void Remove(TKey key)
{
//check if key exists, throw exception if not
var value = dictionary[key];
dictionary.Remove(key);
valueSet.Remove(value);
}
I often find myself creating a Dictionary with a non-trivial value class (e.g. List), and then always writing the same code pattern when filling in data.
For example:
var dict = new Dictionary<string, List<string>>();
string key = "foo";
string aValueForKey = "bar";
That is, I want to insert "bar" into the list that corresponds to key "foo", where key "foo" might not be mapped to anything.
This is where I use the ever-repeating pattern:
List<string> keyValues;
if (!dict.TryGetValue(key, out keyValues))
dict.Add(key, keyValues = new List<string>());
keyValues.Add(aValueForKey);
Is there a more elegant way of doing this?
Related questions that don't have answers to this question:
Is there an IDictionary implementation that returns null on missing key instead of throwing?
Find-or-insert with only one lookup in c# dictionary
Dictionary returning a default value if the key does not exist
We have a slightly different take on this, but the effect is similar:
public static TValue GetOrCreate<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key)
where TValue : new()
{
if (!dict.TryGetValue(key, out TValue val))
{
val = new TValue();
dict.Add(key, val);
}
return val;
}
Called:
var dictionary = new Dictionary<string, List<int>>();
List<int> numbers = dictionary.GetOrCreate("key");
It makes use of the generic constraint for public parameterless constructors: where TValue : new().
To help with discovery, unless the extension method is quite specific to a narrow problem, we tend to place extension methods in the namespace of the type they are extending, in this case:
namespace System.Collections.Generic
Most of the time, the person using the type has the using statement defined at the top, so IntelliSense would also find the extension methods for it defined in your code.
As with so many programming problems, when you find yourself doing something a lot, refactor it into a method:
public static void MyAdd<TKey, TCollection, TValue>(
this Dictionary<TKey, TCollection> dictionary, TKey key, TValue value)
where TCollection : ICollection<TValue>, new()
{
TCollection collection;
if (!dictionary.TryGetValue(key, out collection))
{
collection = new TCollection();
dictionary.Add(key, collection);
}
collection.Add(value);
}
If you use .Net Core you can use Dictionary<>.TryAdd().
var dict = new Dictionary<string, string>();
dict.TryAdd("foo", "bar"); // returns bool whether it added or not feel free to ignore.
var myValue = dict["foo"];
Here is a solution in case the constructor requires a parameter.
public static TValue GetOrCreate<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, Func<TValue> createNew)
{
if (!dict.TryGetValue(key, out var val))
{
val = createNew();
dict.Add(key, val);
}
return val;
}
Simple to use:
MyDict.GetOrCreate(si.Id, createNew: () => new ObjectKnowingItsId(si.Id))
For further readers, here are some extensions in every flavour I thought fit. You could also do something with an out parameter if you need to check if you have added a value but i think you can use containskey or something already for that.
You can use GetOrAddNew to retrieve an item, or create and add it to the dict. You can use the various overloads of GetOrAdd to add a new value. This could be the default so e.g. NULL or 0 but you can also provide a lambda to construct an object for you, with any kind of constructor arguments you'd like.
var x = new Dictionary<string, int>();
var val = x.GetOrAdd("MyKey", (dict, key) => dict.Count + 2);
var val2 = x.GetOrAdd("MyKey", () => Convert.ToInt32("2"));
var val3 = x.GetOrAdd("MyKey", 1);
/// <summary>
/// Extensions for dealing with <see cref="Dictionary{TKey,TValue}"/>
/// </summary>
public static class DictionaryExtensions
{
public static TValue GetOrAddNew<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, TValue defaultValue = default)
where TValue : new()
=> dict.GetOrAdd(key, (values, innerKey) => EqualityComparer<TValue>.Default.Equals(default(TValue), defaultValue) ? new TValue() : defaultValue);
public static TValue GetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, TValue defaultValue = default)
=> dict.GetOrAdd(key, (values, innerKey) => defaultValue);
public static TValue GetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, Func<TValue> valueProvider)
=> dict.GetOrAdd(key, (values, innerKey) => valueProvider());
public static TValue GetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, Func<TKey, TValue> valueProvider)
=> dict.GetOrAdd(key, (values, innerKey) => valueProvider(key));
public static TValue GetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, Func<IDictionary<TKey, TValue>, TKey, TValue> valueProvider)
{
if (dict == null) throw new ArgumentNullException(nameof(dict));
if (key == null) throw new ArgumentNullException(nameof(key));
if (valueProvider == null) throw new ArgumentNullException(nameof(valueProvider));
if (dict.TryGetValue(key, out var foundValue))
return foundValue;
dict[key] = valueProvider(dict, key);
return dict[key];
}
}
And what about this?
var keyValues = dictionary[key] = dictionary.ContainsKey(key) ? dictionary[key] : new List<string>();
keyValues.Add(aValueForKey);
Slight twist
Had a special need that was a literal match to the question, but maybe not its intent. For this case, getting the value was expensive (reflection) and only wanted to generate the value once, to populate the dictionary for caching. Building off #adam-houldsworth answer, the value argument was modified into a delegate.
public static TValue GetOrCreate<TKey, TValue>(
this IDictionary<TKey, TValue> self,
TKey key,
Func<TValue> getValue)
{
if (self == null)
{
throw new ArgumentNullException(nameof(self));
}
else if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
else if (!self.ContainsKey(key))
{
self[key] = getValue() ;
}
return self[key];
}
Usage
var assemblyName = callingAssemblies.GetOrCreate
(
path,
() => Assembly.GetCallingAssembly().GetName().Name
);
Ok, different approach:
public static bool TryAddValue<TKey,TValue>(this System.Collections.Generic.IDictionary<TKey,List<TValue>> dictionary, TKey key, TValue value)
{
// Null check (useful or not, depending on your null checking approach)
if (value == null)
return false;
List<TValue> tempValue = default(List<TValue>);
try
{
if (!dictionary.TryGetValue(key, out tempValue))
{
dictionary.Add(key, tempValue = new List<TValue>());
}
else
{
// Double null check (useful or not, depending on your null checking approach)
if (tempValue == null)
{
dictionary[key] = (tempValue = new List<TValue>());
}
}
tempValue.Add(value);
return true;
}
catch
{
return false;
}
}
In this way you have to "try to add" your value to a generic List of (obviously generalizable to a generic collection), null checking and trying to get existing key/values in your Dictionary.
Usage and example:
var x = new Dictionary<string,List<string>>();
x.TryAddValue("test", null); // return false due to null value. Doesn't add the key
x.TryAddValue("test", "ok"); // it works adding the key/value
x.TryAddValue("test", "ok again"); // it works adding the value to the existing list
Hope it helps.
I am missing the GetOrAdd for Dictionary, that does exist for ConcurrentDictionary.
ConcurrentDictionary<int,Guid> Conversion = new ConcurrentDictionary<int, Guid>();
List<int> before = new List<int> { 1, 2, 1, 3 };
List<Guid> after = before.Select(x => Conversion.GetOrAdd(x, Guid.NewGuid())).ToList();
This code will generate Guids for each number. Ending up converting both 1's in before to the same Guid.
In your case:
ConcurrentDictionary<int, List<String>> dict;
keyValues = dict.GetOrAdd(key, new List<String>());
keyValues.Add(aValueForKey);
using System.Runtime.InteropServices;
public static TValue GetOrCreate<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key, Func<TValue> valueProvider)
where TKey: notnull
{
ref var value = ref CollectionsMarshal.GetValueRefOrAddDefault(dictionary, key, out bool exists);
if (!exists) value = valueProvider.Invoke();
return value!;
}
public static TValue GetOrCreate<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key, TValue value)
where TKey: notnull
=> GetOrCreate(dictionary, key, () => value);
public static TValue GetOrCreate<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key)
where TKey: notnull
where TValue : new()
=> GetOrCreate(dictionary, key, new TValue());
To avoid duplicate hash lookups.
You can find more info here.
ConcurrentDictionary.GetOrAdd does exactly what is being asked.
Initialization
ConcurrentDictionary<string, List<string>> dict = new();
Usage
var list = dict.GetOrAdd(key, _ => new List<string>());
Notice how we are using a factory method to create a new list as-need. This prevents pre-allocating a list on each call to GetOrAdd.
This question already has answers here:
Is there an IDictionary implementation that, on missing key, returns the default value instead of throwing?
(17 answers)
Closed 9 years ago.
I find myself using the current pattern quite often in my code nowadays
var dictionary = new Dictionary<type, IList<othertype>>();
// Add stuff to dictionary
var somethingElse = dictionary.ContainsKey(key) ? dictionary[key] : new List<othertype>();
// Do work with the somethingelse variable
Or sometimes
var dictionary = new Dictionary<type, IList<othertype>>();
// Add stuff to dictionary
IList<othertype> somethingElse;
if(!dictionary.TryGetValue(key, out somethingElse) {
somethingElse = new List<othertype>();
}
Both of these ways feel quite roundabout. What I really would like is something like
dictionary.GetValueOrDefault(key)
Now, I could write an extension method for the dictionary class that does this for me, but I figured that I might be missing something that already exists. SO, is there a way to do this in a way that is more "easy on the eyes" without writing an extension method to dictionary?
TryGetValue will already assign the default value for the type to the dictionary, so you can just use:
dictionary.TryGetValue(key, out value);
and just ignore the return value. However, that really will just return default(TValue), not some custom default value (nor, more usefully, the result of executing a delegate). There's nothing more powerful built into the framework. I would suggest two extension methods:
public static TValue GetValueOrDefault<TKey, TValue>(
this IDictionary<TKey, TValue> dictionary,
TKey key,
TValue defaultValue)
{
return dictionary.TryGetValue(key, out var value) ? value : defaultValue;
}
public static TValue GetValueOrDefault<TKey, TValue>(
this IDictionary<TKey, TValue> dictionary,
TKey key,
Func<TValue> defaultValueProvider)
{
return dictionary.TryGetValue(key, out var value) ? value : defaultValueProvider();
}
(You may want to put argument checking in, of course :)
I do favor extension methods, but here's a simple class I use from time to time to handle dictionaries when I need default values.
I wish this were just part of the base Dictionary class.
public class DictionaryWithDefault<TKey, TValue> : Dictionary<TKey, TValue>
{
TValue _default;
public TValue DefaultValue {
get { return _default; }
set { _default = value; }
}
public DictionaryWithDefault() : base() { }
public DictionaryWithDefault(TValue defaultValue) : base() {
_default = defaultValue;
}
public new TValue this[TKey key]
{
get {
TValue t;
return base.TryGetValue(key, out t) ? t : _default;
}
set { base[key] = value; }
}
}
Beware, however. By subclassing and using new (since override is not available on the native Dictionary type), if a DictionaryWithDefault object is upcast to a plain Dictionary, calling the indexer will use the base Dictionary implementation (throwing an exception if missing) rather than the subclass's implementation.
I created a DefaultableDictionary to do exactly what you are asking for!
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace DefaultableDictionary {
public class DefaultableDictionary<TKey, TValue> : IDictionary<TKey, TValue> {
private readonly IDictionary<TKey, TValue> dictionary;
private readonly TValue defaultValue;
public DefaultableDictionary(IDictionary<TKey, TValue> dictionary, TValue defaultValue) {
this.dictionary = dictionary;
this.defaultValue = defaultValue;
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() {
return dictionary.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
public void Add(KeyValuePair<TKey, TValue> item) {
dictionary.Add(item);
}
public void Clear() {
dictionary.Clear();
}
public bool Contains(KeyValuePair<TKey, TValue> item) {
return dictionary.Contains(item);
}
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) {
dictionary.CopyTo(array, arrayIndex);
}
public bool Remove(KeyValuePair<TKey, TValue> item) {
return dictionary.Remove(item);
}
public int Count {
get { return dictionary.Count; }
}
public bool IsReadOnly {
get { return dictionary.IsReadOnly; }
}
public bool ContainsKey(TKey key) {
return dictionary.ContainsKey(key);
}
public void Add(TKey key, TValue value) {
dictionary.Add(key, value);
}
public bool Remove(TKey key) {
return dictionary.Remove(key);
}
public bool TryGetValue(TKey key, out TValue value) {
if (!dictionary.TryGetValue(key, out value)) {
value = defaultValue;
}
return true;
}
public TValue this[TKey key] {
get
{
try
{
return dictionary[key];
} catch (KeyNotFoundException) {
return defaultValue;
}
}
set { dictionary[key] = value; }
}
public ICollection<TKey> Keys {
get { return dictionary.Keys; }
}
public ICollection<TValue> Values {
get
{
var values = new List<TValue>(dictionary.Values) {
defaultValue
};
return values;
}
}
}
public static class DefaultableDictionaryExtensions {
public static IDictionary<TKey, TValue> WithDefaultValue<TValue, TKey>(this IDictionary<TKey, TValue> dictionary, TValue defaultValue ) {
return new DefaultableDictionary<TKey, TValue>(dictionary, defaultValue);
}
}
}
This project is a simple decorator for an IDictionary object and an extension method to make it easy to use.
The DefaultableDictionary will allow for creating a wrapper around a dictionary that provides a default value when trying to access a key that does not exist or enumerating through all the values in an IDictionary.
Example: var dictionary = new Dictionary<string, int>().WithDefaultValue(5);
Blog post on the usage as well.
No, nothing like that exists. The extension method is the way to go, and your name for it (GetValueOrDefault) is a pretty good choice.
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
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.
Yes, define a class that adds the object to an internal hashtable with both keys,
public MyClass<k1, k2, T>: Dictionary<object, T>
{
private Dictionary<k1, k2> keyMap;
public new Add(k1 key1Val, k2 key2Val, T object)
{
keyMap.Add(key1Val, key2Val);
base.Add(k2, object)
}
public Remove(k1 key1Val)
{
base.Remove(keyMap[key1Val]);
keyMap.Remove(key1Val);
}
public Remove(k2 key2Val)
{
base.Remove(key2Val);
keyMap.Remove(key2Val);
}
}
There's nothing built into .NET BCL for this type of collection at the moment.
I see two options:
Use a two-level dictionary. The first level maps different keys to some common unique key (let's say a GUID), and the second level maps the GUID to the actual value.
Create a custom key class and implement Equals() and GetHashCode() so that any one component of the key is sufficient to find the entire key. You could then supply helper methods to construct instances of the key using only one of the values so that you could do lookups.
Another simple (and effective) implementation would be to use PowerCollections' Pair<TFirst, TSecond> type as a dictionary key, something like
Dictionary<Pair<TKey1, TKey2>, TValue> foo;
foo.Add(new Pair<TKey1, TKey2>(key1, key2), value);
Pair<> implements Equals and GetHashCode consistently, so you don't need to resort to multi-level dictionaries (which are more cumbersome and probably less effective).
There's also a Triple<TFirst, TSecond, TThird> if you need a 3-key dictionary.
I find many answers here unnecessarily complex, less performant or plain unusable. The best approach would be to have a KeyValuePair<> of the secondary key and the value clubbed together as the Value of either dictionaries. This lets you have just one lookup for for removal and updation operations. A straightforward implementation:
public class DualDictionary<TKey1, TKey2, TValue> : IEnumerable<KeyValuePair<Tuple<TKey1, TKey2>, TValue>>
{
Dictionary<TKey1, KeyValuePair<TKey2, TValue>> _firstKeys;
Dictionary<TKey2, KeyValuePair<TKey1, TValue>> _secondKeys;
public int Count
{
get
{
if (_firstKeys.Count != _secondKeys.Count)
throw new Exception("somewhere logic went wrong and your data got corrupt");
return _firstKeys.Count;
}
}
public ICollection<TKey1> Key1s
{
get { return _firstKeys.Keys; }
}
public ICollection<TKey2> Key2s
{
get { return _secondKeys.Keys; }
}
public IEnumerable<TValue> Values
{
get { return this.Select(kvp => kvp.Value); }
}
public DualDictionary(IEqualityComparer<TKey1> comparer1 = null, IEqualityComparer<TKey2> comparer2 = null)
{
_firstKeys = new Dictionary<TKey1, KeyValuePair<TKey2, TValue>>(comparer1);
_secondKeys = new Dictionary<TKey2, KeyValuePair<TKey1, TValue>>(comparer2);
}
public bool ContainsKey1(TKey1 key)
{
return ContainsKey(key, _firstKeys);
}
private static bool ContainsKey<S, T>(S key, Dictionary<S, KeyValuePair<T, TValue>> dict)
{
return dict.ContainsKey(key);
}
public bool ContainsKey2(TKey2 key)
{
return ContainsKey(key, _secondKeys);
}
public TValue GetValueByKey1(TKey1 key)
{
return GetValueByKey(key, _firstKeys);
}
private static TValue GetValueByKey<S, T>(S key, Dictionary<S, KeyValuePair<T, TValue>> dict)
{
return dict[key].Value;
}
public TValue GetValueByKey2(TKey2 key)
{
return GetValueByKey(key, _secondKeys);
}
public bool TryGetValueByKey1(TKey1 key, out TValue value)
{
return TryGetValueByKey(key, _firstKeys, out value);
}
private static bool TryGetValueByKey<S, T>(S key, Dictionary<S, KeyValuePair<T, TValue>> dict, out TValue value)
{
KeyValuePair<T, TValue> otherPairing;
bool b = TryGetValue(key, dict, out otherPairing);
value = otherPairing.Value;
return b;
}
private static bool TryGetValue<S, T>(S key, Dictionary<S, KeyValuePair<T, TValue>> dict,
out KeyValuePair<T, TValue> otherPairing)
{
return dict.TryGetValue(key, out otherPairing);
}
public bool TryGetValueByKey2(TKey2 key, out TValue value)
{
return TryGetValueByKey(key, _secondKeys, out value);
}
public bool Add(TKey1 key1, TKey2 key2, TValue value)
{
if (ContainsKey1(key1) || ContainsKey2(key2)) // very important
return false;
AddOrUpdate(key1, key2, value);
return true;
}
// dont make this public; a dangerous method used cautiously in this class
private void AddOrUpdate(TKey1 key1, TKey2 key2, TValue value)
{
_firstKeys[key1] = new KeyValuePair<TKey2, TValue>(key2, value);
_secondKeys[key2] = new KeyValuePair<TKey1, TValue>(key1, value);
}
public bool UpdateKey1(TKey1 oldKey, TKey1 newKey)
{
return UpdateKey(oldKey, _firstKeys, newKey, (key1, key2, value) => AddOrUpdate(key1, key2, value));
}
private static bool UpdateKey<S, T>(S oldKey, Dictionary<S, KeyValuePair<T, TValue>> dict, S newKey,
Action<S, T, TValue> updater)
{
KeyValuePair<T, TValue> otherPairing;
if (!TryGetValue(oldKey, dict, out otherPairing) || ContainsKey(newKey, dict))
return false;
Remove(oldKey, dict);
updater(newKey, otherPairing.Key, otherPairing.Value);
return true;
}
public bool UpdateKey2(TKey2 oldKey, TKey2 newKey)
{
return UpdateKey(oldKey, _secondKeys, newKey, (key1, key2, value) => AddOrUpdate(key2, key1, value));
}
public bool UpdateByKey1(TKey1 key, TValue value)
{
return UpdateByKey(key, _firstKeys, (key1, key2) => AddOrUpdate(key1, key2, value));
}
private static bool UpdateByKey<S, T>(S key, Dictionary<S, KeyValuePair<T, TValue>> dict, Action<S, T> updater)
{
KeyValuePair<T, TValue> otherPairing;
if (!TryGetValue(key, dict, out otherPairing))
return false;
updater(key, otherPairing.Key);
return true;
}
public bool UpdateByKey2(TKey2 key, TValue value)
{
return UpdateByKey(key, _secondKeys, (key1, key2) => AddOrUpdate(key2, key1, value));
}
public bool RemoveByKey1(TKey1 key)
{
return RemoveByKey(key, _firstKeys, _secondKeys);
}
private static bool RemoveByKey<S, T>(S key, Dictionary<S, KeyValuePair<T, TValue>> keyDict,
Dictionary<T, KeyValuePair<S, TValue>> valueDict)
{
KeyValuePair<T, TValue> otherPairing;
if (!TryGetValue(key, keyDict, out otherPairing))
return false;
if (!Remove(key, keyDict) || !Remove(otherPairing.Key, valueDict))
throw new Exception("somewhere logic went wrong and your data got corrupt");
return true;
}
private static bool Remove<S, T>(S key, Dictionary<S, KeyValuePair<T, TValue>> dict)
{
return dict.Remove(key);
}
public bool RemoveByKey2(TKey2 key)
{
return RemoveByKey(key, _secondKeys, _firstKeys);
}
public void Clear()
{
_firstKeys.Clear();
_secondKeys.Clear();
}
public IEnumerator<KeyValuePair<Tuple<TKey1, TKey2>, TValue>> GetEnumerator()
{
if (_firstKeys.Count != _secondKeys.Count)
throw new Exception("somewhere logic went wrong and your data got corrupt");
return _firstKeys.Select(kvp => new KeyValuePair<Tuple<TKey1, TKey2>, TValue>(Tuple.Create(kvp.Key, kvp.Value.Key),
kvp.Value.Value)).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
Few things to note:
I have implemented only IEnumerable<>. I don't think ICollection<> makes sense here since the method names all could be way different for this special collection structure. Up to you to decide what should go inside IEnumerable<>.
I have attempted for some weird exceptions to be thrown here and there - just for data integrity. Just to be on the safer side so that you know if ever my code has bugs.
I have named methods in such a way that its compilable even when Key1 and Key2 are of the same type.
Performance: You can lookup for Value with either of the Keys. Get and Contains method require just 1 lookup (O(1)). Add requires 2 lookups and 2 adds. Update requires 1 lookup and 2 adds. Remove takes 3 lookups.
I tried this and it works perfectly (include add, remove & indexer)
public class MultikeyDictionary<K1, K2, V> : Dictionary<KeyValuePair<K1, K2>, V>
{
public V this[K1 index1, K2 index2]
{
get
{
return this[new KeyValuePair<K1, K2>(index1, index2)];
}
set
{
this[new KeyValuePair<K1, K2>(index1, index2)] = value;
}
}
public bool Remove(K1 index1, K2 index2)
{
return base.Remove(new KeyValuePair<K1,K2>(index1, index2));
}
public void Add(K1 index1, K2 index2, V value)
{
base.Add(new KeyValuePair<K1, K2>(index1, index2), value);
}
}
and even I extended it to 4 values:
public class MultikeyDictionary<K1, K2, K3, V> : MultikeyDictionary<KeyValuePair<K1, K2>, K3, V>
{
public V this[K1 index1, K2 index2, K3 index3]
{
get
{
return base[new KeyValuePair<K1, K2>(index1, index2), index3];
}
set
{
base[new KeyValuePair<K1, K2>(index1, index2), index3] = value;
}
}
public bool Remove(K1 index1, K2 index2, K3 index3)
{
return base.Remove(new KeyValuePair<K1, K2>(index1, index2), index3);
}
public void Add(K1 index1, K2 index2, K3 index3, V value)
{
base.Add(new KeyValuePair<K1, K2>(index1, index2), index3, value);
}
}
Enjoy,
Ofir
Sure, it's an OO language and you can implement whatever O's you want. You are going to have some ambiguity to resolve (what if TKey1 and TKey2 are the same type, which methods get called then?)
You won't be able to define the overloads for both types, and the generics system doesn't allow for an arbitrary number of types (like methods allow params). So, you'd be stuck with a set of classes which defined 2, 3, 4, etc. simultaneous keys. Additionally, you'd have to use object as the parameter for get and set, using runtime type checks to simulate the overload.
Additionally, you'd only store one dictionary of <TKEY1,VAL>, the other dictionaries would be of <TKEY2,TKEY1>, <TKEY3,TKEY1> and would act as indexes on the main dictionary.
It's mostly boiler plate code.
You may find my IndexMap implementation to be a good base for rewriting it from Java into C#. The programming model isn't as elegant as I'd prefer, but it isn't meant for developing with directly. Rather it lies behind a caching library which supplies standard annotations to allow for a succinct coding style. By using the Map interface it provides a clean compositional model when combining it with self-populating, expirational, and evictible map decorators. I am sure that someone could come up with a nice programming interface for direct usage where it is acceptable to lose the benefit of the Map interface.
Not a direct solution and not viable for multi keys, but worked for my use case.
Dictionary<Guid, Object> objs = new Dictionary<Guid, Object>();
Dictionary<int, Guid> guids = new Dictionary<int, Guid>();
private void Set(object sender, Object obj)
{
objs[obj.Guid] = obj;
guids[obj.Id] = obj.Guid;
}
public Object Get(int id)
{
return guids.ContainsKey(id) ? Get(guids[id]) : null;
}
public Object Get(Guid guid)
{
return objs.ContainsKey(guid) ? objs[guid] : null;
}
I wrote a MultiKeyDictionary package for net472, net481, netstandard2.1, and net6.0.
In this version, however, you can combine key1 with arbitrary key2s. You can slice, contains, add, remove, clear, set, index, trygetvalue, tryslice, and enumerate. There's a maximum of 5 keys supported.