Author : MD TAREQ HASSAN | Updated : 2021/03/22

Dictionary syntax

// Creating dictionary
Dictionary<int, string> dict = new Dictionary<int, string>()
var dict = new Dictionary<int, string>()

// adding value
dict[0] = "foo";
dict[1] = "bar";

//reading value
var foo = dict[0]

Links

Initialization

// Initialization
var dictionary = new Dictionary<int, string>{ {1, "One"}, {2, "Two"} }
// new dictionary initializer
var dictionary = new Dictionary<int, string> {
     [1] = "One",
     [2] = "Two"
}

Property

// Property 
dictionary.Count

dictionary.Values

Looping

// Looping
foreach(var keyValuePair in itemsDict){
  var key = keyValuePair.Key;
  var val = keyValuePair.Value;
}

// Iterate over values
foreach (var value in dictionary.Values) {
    Console.WriteLine(value);
}
// Iterate over dictionary
foreach (var keyValuePair in dictionary) {
    Console.WriteLine(keyValuePair.Key);
    Console.WriteLine(keyValuePair.Value);
}

Operations

// O(1) operations
dictionary.Add(key, value);    // might be O(n) too
// get
string val = dictionary[key];
if (dictionary.TryGetValue(key, var out valForKey)) {
}
// contains key 
var containsKey = dictionary.ContainsKey(key);
// remove by key
dictionary.Remove(key);
// remove all
dictionary.Clear();


// O(n) operations
// contains value
var containsValue = dictionary.ContainsValue(val);
// Iterate over keys 
foreach (var key in dictionary.Keys){
    Console.WriteLine(dictionary[key]);
}

Find duplicates using dictionary

    var items = new int[] { 2, 3, 1, 4, 5, 1, 2, 3, 1, 1};

    var itemsDict = new Dictionary<int, int>();

    foreach(var item in items){
      if(itemsDict.ContainsKey(item)){ // found duplicate
        itemsDict[item] += 1;
      } else {
        itemsDict[item] = 1;
      }
    }

    foreach(var keyValuePair in itemsDict){
      Console.WriteLine($"item {keyValuePair.Key} appeared {keyValuePair.Value} times");
    }

Dictionary to string

var fooDict = new Dictionary<string, string> {
  [b] = "bar",
  [x] = "bax"
};
string fooStr = string.Join(";", fooDict.Select(kv => kv.Key + "=" + kv.Value).ToArray());

String to dictionary

var fooStr = "b=bar;x=bax";
var fooDict = text.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries)
               .Select(part => part.Split('='))
               .ToDictionary(split => split[0], split => split[1]);

Dictionary to array

var array = dict.Values.ToArray();
var array = dict.Keys.ToArray();

T[] array = new T[dict.Count];
dict.Values.CopyTo(array, 0); // starting from 0 index

// using LINQ - has overhead (calling Lambda each time)
var array = dict.Select(pair => pair.Value).ToArray();

Array to dictionary

var dict = array.ToDictionary(key => key, value => value); // key == value == each item

// to avoid duplicate key, use index as key
var dictionary = array.Select((v, i) => new {Key = i, Value = v}).ToDictionary(o => o.Key, o => o.Value);

// to avoid duplicate key, use hashset
var hashset = new HashSet<string>(array);
var dict = hashset.ToDictionary(key => key, value => value);

Dictionary to list

var keyList = dictionary.Keys.ToList();
var valList = dictionary.Values.ToList();

// key value pair
List<KeyValuePair<string, int>> list = dictionary.ToList();

foreach (KeyValuePair<string, int> pair in list){
  Console.WriteLine(pair.Key);
  Console.WriteLine(pair.Value);
}

// when values are nested list
Dictionary<K, List<V>> dictionary = GetDictionary();
List<List<V>> nestedList = dictionary.Values;
List<V> list = nestedList.SelectMany(item => item).ToList();

List to dictionary

var dict = list.ToDictionary(x => x, x => x);

// to avoid duplicate key
var dict = list.Distinct().ToDictionary(x => x, x => x);  // var hashset = new HashSet<string>(list);
var dict = list.ToLookup(x => x);