text
stringlengths
0
13.4k
string value = null;
bool success = dict.TryGetValue(1, out value);
Getting or Adding a value
There are two mehod overloads, that will get or add a value in a thread-safe manner.
Get value with key 2, or add value "Second" if the key is not present:
string theValue = dict.GetOrAdd(2, "Second");
Using a factory for adding a value, if value is not present:
string theValue2 = dict.GetOrAdd(2, (key) => key == 2 ? "Second" : "Not Second." );
Section 4.8: Dictionary to List
Creating a list of KeyValuePair:
Dictionary<int, int> dictionary = new Dictionary<int, int>();
List<KeyValuePair<int, int>> list = new List<KeyValuePair<int, int>>();
list.AddRange(dictionary);
Creating a list of keys:
Dictionary<int, int> dictionary = new Dictionary<int, int>();
List<int> list = new List<int>();
list.AddRange(dictionary.Keys);
Creating a list of values:
Dictionary<int, int> dictionary = new Dictionary<int, int>();
List<int> list = new List<int>();
list.AddRange(dictionary.Values);
Section 4.9: Removing from a Dictionary
Given this setup code:
var dict = new Dictionary<int, string>()
{
{ 1, "First" },
{ 2, "Second" },
{ 3, "Third" }
};
GoalKicker.com – .NET Framework Notes for Professionals
16
Use the Remove method to remove a key and its associated value.
bool wasRemoved = dict.Remove(2);
Executing this code removes the key 2 and it's value from the dictionary. Remove returns a boolean value indicating
whether the specified key was found and removed from the dictionary. If the key does not exist in the dictionary,
nothing is removed from the dictionary, and false is returned (no exception is thrown).
It's incorrect to try and remove a key by setting the value for the key to null.
dict[2] = null; // WRONG WAY TO REMOVE!
This will not remove the key. It will just replace the previous value with a value of null.
To remove all keys and values from a dictionary, use the Clear method.
dict.Clear();
After executing Clear the dictionary's Count will be 0, but the internal capacity remains unchanged.
Section 4.10: ContainsKey(TKey)
To check if a Dictionary has an specifique key, you can call the method ContainsKey(TKey) and provide the key of
TKey type. The method returns a bool value when the key exists on the dictionary. For sample:
var dictionary = new Dictionary<string, Customer>()
{
{"F1", new Customer() { FirstName = "Felipe", ... } },
{"C2", new Customer() { FirstName = "Carl", ... } },
{"J7", new Customer() { FirstName = "John", ... } },
{"M5", new Customer() { FirstName = "Mary", ... } },
};
And check if a C2 exists on the Dictionary:
if (dictionary.ContainsKey("C2"))
{
// exists
}
The ContainsKey method is available on the generic version Dictionary<TKey, TValue>.
Section 4.11: ConcurrentDictionary augmented with Lazy'1
reduces duplicated computation
Problem