Property : dictionary.Count
Initialization
var dictionary = new Dictionary<int, string>{ {1, "One"}, {2, "Two"} }
// new dictionary initializer
var dictionary = new Dictionary<int, string>{
[1] = "One",
[2] = "Two"
}
O(1) operations
// add => might be O(n) too
dictionary.Add(key, value);
// 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]);
// 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);
}
Runtime Complexity of .NET Generic Collection
Conversion to string
dictionary to string
string str = string.Join(";", myDict.Select(kv => kv.Key + "=" + kv.Value).ToArray());
string to dictionary
var dict = text.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries)
.Select(part => part.Split('='))
.ToDictionary(split => split[0], split => split[1]);
Conversion to array
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);
Conversion to list
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 dict = list.ToLookup(x => x);