C# Dictionary

Dictionary<T,T> is similar to the hash arrays of other programming languages. It is a generic class, where T can be any data types.

using System.Collections.Generic;
Dictionary<string, int> d = new Dictionary<string, int> {
{"Jacobs",28},{"Mary",26}
};
Dictionary<string, int> d2 = new Dictionary<string, int>();
d2.Add("Mary",26);
d2.Add("Chris",32);
d2["John"] = 23;

Useful Dictionary<T,T> methods and properties:
void d.Add(string str, int n);
bool d.ContainsKey(string str);
bool d.ContainsValue(int n);
bool d.Remove(string str);
void d.Clear();
int d.Count;

Useful Dictionary<T,T> methods and properties examples:
using System.Collections.Generic;
Dictionary<string, int> d = new Dictionary<string, int> {
{"Jacobs",28},{"Mary",26}
};
d.Remove("Mary");
d.ContainsKey("Jacobs"); //true
d.ContainsValue(28); //true

Loop through the dictionary:
using System.Collections.Generic;
Dictionary<string, int> d = new Dictionary<string, int> {
{"Jacobs",28},{"Mary",26}
};
foreach (KeyValuePair<string, int> p in d)
{
string name = p.Key;
int age = p.Value;
}



endmemo.com © 2017  Terms of Use | Home