How to use SortedDictionary Properties with C#

The SortedDictionary class has three properties - Count, Keys and Values.

Count

The Count property gets the number of key/value pairs in a SortedDictionary.

The following code snippet display number of items in a SortedDictionary.

Console.WriteLine("Count: {0}", AuthorList.Count);

 

Item

The Item property gets and sets the value associated with the specified key.

The following code snippet sets and gets an items value.

// Set Item value

AuthorList["Mahesh Chand"] = 20;

// Get Item value

Int16 age = Convert.ToInt16(AuthorList["Mahesh Chand"]);

 

Keys

The Keys property gets a collection containing the keys in the SortedDictionary. It returns an object of KeyCollection type.

The following code snippet reads all keys in a SortedDictionary.  

// Get and display keys

SortedDictionary<string, Int16>.KeyCollection keys = AuthorList.Keys;

foreach (string key in keys)

{

    Console.WriteLine("Key: {0}", key);

}

 
Values

The Values property gets a collection containing the values in the SortedDictionary. It returns an object of ValueCollection type.

The following code snippet reads all values in a SortedDictionary. 

// Get and display values

SortedDictionary<string, Int16>.ValueCollection values = AuthorList.Values;

foreach (Int16 val in values)

{

    Console.WriteLine("Value: {0}", val);

}


Learn more:

Working with SortedDictionary using C#




Similar Articles