Tutorial by Examples

You can enumerate through a Dictionary in one of 3 ways: Using KeyValue pairs Dictionary<int, string> dict = new Dictionary<int, string>(); foreach(KeyValuePair<int, string> kvp in dict) { Console.WriteLine("Key : " + kvp.Key.ToString() + ", Value : " +...
// Translates to `dict.Add(1, "First")` etc. var dict = new Dictionary<int, string>() { { 1, "First" }, { 2, "Second" }, { 3, "Third" } }; // Translates to `dict[1] = "First"` etc. // Works in C# 6.0. var dict = new Dicti...
Dictionary<int, string> dict = new Dictionary<int, string>(); dict.Add(1, "First"); dict.Add(2, "Second"); // To safely add items (check to ensure item does not already exist - would throw) if(!dict.ContainsKey(3)) { dict.Add(3, "Third"); } Al...
Given this setup code: var dict = new Dictionary<int, string>() { { 1, "First" }, { 2, "Second" }, { 3, "Third" } }; You may want to read the value for the entry with key 1. If key doesn't exist getting a value will throw KeyNotFoundException,...
var MyDict = new Dictionary<string,T>(StringComparison.InvariantCultureIgnoreCase)
Represents a thread-safe collection of key/value pairs that can be accessed by multiple threads concurrently. Creating an instance Creating an instance works pretty much the same way as with Dictionary<TKey, TValue>, e.g.: var dict = new ConcurrentDictionary<int, string>(); Ad...
Create a Dictionary<TKey, TValue> from an IEnumerable<T>: using System; using System.Collections.Generic; using System.Linq; public class Fruits { public int Id { get; set; } public string Name { get; set; } } var fruits = new[] { new Fruits { Id = 8 , Nam...
Given this setup code: var dict = new Dictionary<int, string>() { { 1, "First" }, { 2, "Second" }, { 3, "Third" } }; Use the Remove method to remove a key and its associated value. bool wasRemoved = dict.Remove(2); Executing this code remo...
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 Custom...
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 ...
Problem ConcurrentDictionary shines when it comes to instantly returning of existing keys from cache, mostly lock free, and contending on a granular level. But what if the object creation is really expensive, outweighing the cost of context switching, and some cache misses occur? If the same key ...

Page 1 of 1