CollectionDictionary class
A Dictionary implementation that stores multiple values for each key.
The Dictionary
class is one of the most-used data structures in .NET applications. It allows you to store a single value for every key. This 1:1 mapping is often sufficient. But sometimes you need to keep multiple values for a key. This is what the simple CollectionDictionary
class does. It directly inherits from Dictionary<TKey, ICollection<TValue>>
and adds methods to handle multi-value entries. Since no methods are overridden or hidden, the base class methods from Dictionary
is also available. In that case you get a Dictionary
with a collection as the value.
Compatibility:
Example
The following sample code snippets show the usage of the CollectionDictionary class:
var dict = new CollectionDictionary<string, string>();
// Create a new instance from an existing Dictionary
var simpleDict = new Dictionary<string, int>();
var dict2 = new CollectionDictionary<string, int>(simpleDict);
// Add a new key with a value
dict.Add("Germany", "Berlin");
dict.Add("France", "Paris");
dict.Add("Italy", "Rome");
// Add more values to existing keys
dict.Add("Germany", "Munich");
dict.Add("Germany", "Cologne");
dict.AddRange("France", new[] { "Reims", "Marseille", "Toulouse" });
// Remove a key with all values (inherited from Dictionary)
dict.Remove("Italy");
// Remove a value
// (A key with no remaining values is automatically removed)
dict.RemoveValue("Germany", "Cologne");
// Get all values from an existing key
foreach (string city in dict["Germany"])
{
Console.WriteLine(city);
}
// Get all values from a key (existing or not)
foreach (string city in dict.GetValuesOrEmpty("Germany"))
{
Console.WriteLine(city);
}
// Get the number of keys and values
int keyCount = dict.Count;
int valueCount = dict.ValueCount;
// Search for a key (inherited from Dictionary)
bool countryExists = dict.Contains("France");
// Search for a value
bool cityExists = dict.ContainsValue("Marseille");
Download
CollectionDictionary.cs7.7 KiBSource code of the CollectionDictionary class
Licence and terms of use
Copying and distribution of this file, with or without modification, are permitted provided the copyright notice and this notice are preserved. This file is offered as-is, without any warranty. (GNU All-Permissive licence)
Statistic data
- Created on 2014-09-18, updated on 2015-01-25.
- Ca. 110 lines of code, estimated development costs: 110 - 440 €