Monday, May 18, 2009

C# - Generic dictionary Types - Dictionary


Dictionary Class
Represents a collection of keys and values.
Namespace: System.Collections.Generic

http://msdn.microsoft.com/en-us/library/xfhwa508.aspx

Sample code:

...
public Dictionary seasonDic =
new Dictionary();
...


Some sample methods to work with Dictionary

// Fill the Dictionary
private void fillSeasonDic()
{
seasonDic.Add("Spring", Color.LightGreen);
seasonDic.Add("Summer", Color.Orange);
seasonDic.Add("Autumn", Color.LightYellow);
seasonDic.Add("Winter", Color.LightBlue);
}

// Using .TryGetType to find [value] corresponding to the [key]
private Color getSeasonColor(string seasonName)
{
Color retColor = Color.White;

if ( ! string.IsNullOrEmpty(seasonName))
if ( ! seasonDic.TryGetValue(seasonName, out retColor)
retColor = Color.White;

return retColor;
}

// Retrieve data from a Dictionary by Enumerator
private string getAllSeasons()
{
StringBuilder sbRetVal = new StringBuilder();

Dictionary.Enumerator sEnum =
seasonDic.GetEnumerator();

while (sEnum.MoveNext())
sbRetVal.AppendLine(sEnum.Current.Key +
": " +
sEnum.Current.Value.Name);

return sbRetVal.ToString();
}

// Use [KeyValuePair] structure in a [foreach] loop
private string getAllColorSeasons()
{
StringBuilder sbRetVal = new StringBuilder();

foreach( KeyValuePair kvp in seasonDic )
sbRetVal.AppendLine(kvp.Value.Name + ": " + kvp.Key);

return sbRetVal.ToString();
}

private void btnGetAllSeason_Click(object sender, EventArgs e)
{
MessageBox.Show( this.getAllSeasons() +
"\r\n" +
this.getAllColorSeasons() );
}

Share/Bookmark

No comments: