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;
}

Dictionary do not have sort methods. Following code can be used to sort the dictionary:
public void SortDictionary(ref Dictionary<string, string> d)
{
	List<string> l = new List<string>();
	Dictionary<string, string> d2 = new Dictionary<string, string>();

	foreach (string s in d.Keys)
	{
		l.Add(s);
	}

	l.Sort();

	for (int i = 0; i < l.Count; i++)
	{
		foreach (string s in d.Keys)
		{
			if (s == l[i])
				d2.Add(s, d[s]);
		}
	}

	d = d2;
}

public void SortDictionary(ref Dictionary<string, int> d)
{
	List<int> l = new List<int>();
	Dictionary<string, int> d2 = new Dictionary<string, int>();

	foreach (int i in d.Values)
	{
		if (!l.Contains(i))
			l.Add(i);
	}

	l.Sort();

	for (int i = l.Count - 1; i >= 0; i--)
	{
		foreach (KeyValuePair<string, int> item in d)
		{
			if (item.Value == l[i])
				d2.Add(item.Key, item.Value);
		}
	}

	d = d2;
}

public Dictionary<string, int> SortDictbyKey(ref Dictionary<string, int> ds)
{
	Dictionary<string, int> ds2 = new Dictionary<string, int>();

	List<string> ls = new List<string>();
	foreach (string val in ds.Keys)
	{
		ls.Add(val);
	}

	ls.Sort();

	for (int i = 0; i < ls.Count; i++)
	{
		foreach (string val in ds.Keys)
		{
			if (val == ls[i])
			{
				ds2.Add(val, ds[val]);
			}
		}
	}
	ds = ds2;

	return ds2;
}

Dictionary<string, int> dd = new Dictionary<string, int>();
SortDictionary(ref dd);


endmemo.com © 2024  | Terms of Use | Privacy | Home