Lot of times I have to create a Dictionary<KeyType, List<ValueType>>
Before I can start using the dictionary I have to first verify that List has been created for that key.
//Can i remove these two lines?
if(!dict.ContainsKey(key))
dict[key]= new List<ValueType>;
//now use the key
dict[key].Add(value);
I know its only "2 lines" of code but it annoys me and I think it can be removed.
I can extend dictionary in someway but before I do it, I want to know if someone has found a clever way to remove the above if
statement.
Basically i want to create a Dictionary<KeyType, Collection<ValueType>>
and start using it right away like dict[key].Add(value)
.
In C#, Dictionary is a generic collection which is generally used to store key/value pairs. The working of Dictionary is quite similar to the non-generic hashtable. The advantage of Dictionary is, it is generic type. Dictionary is defined under System. Collection.
If the value type of the dictionary is nullable, you could add a null value: myDict. Add(key1, null); If the value is non nullable, you can use a default value, either default or some out of range value, depending on your expected meaningful values.
Dictionaries are also initialized using the curly braces {} , and the key-value pairs are declared using the key:value syntax. You can also initialize an empty dictionary by using the in-built dict function. Empty dictionaries can also be initialized by simply using empty curly braces.
The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.
You could create something like Google Java Collection's Multimap... or you could just add an extension method like this:
public static void AddValue<TKey, TValue>
(this IDictionary<TKey, List<TValue>> dictionary, TKey key, TValue value)
{
List<TValue> values;
if (!dictionary.TryGetValue(key, out values))
{
values = new List<TValue>();
dictionary.Add(key, values);
}
values.Add(value);
}
As Bevan says, Lookup
can help as well - but you can only create one with the ToLookup
method, and you can't modify it afterwards. In many cases that's a thoroughly good thing, but if you need a mutable map then you'll ned something like the above.
Have a look at the LookUp
class introduced with Linq in .NET 3.5 - it might be just what you're looking for: a Dictionary
like class that supports multiple items per key.
Perhaps the only significant downside is that you have to have all your elements available in one batch, as LookUp is immutable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With