Home > DeveloperSection > Blogs > C# SortedList Collection

C# SortedList Collection


C# C# 
Ratings:
0 Comment(s)
 3583  View(s)
Rate this:

This below example uses the parameterless constructor, the Add instance method, the ContainsKey and TryGetValue methods, the indexer, the enumerator, the IndexOfKey and IndexOfValue methods, and finally the Count property.

Sample Program that uses SortedList [C#]

 

using System;

using System.Collections.Generic;

 

class Program

{

    static void Main()

    {

            //
            // Created SortedList with keys and values.
            //

            SortedList<string, int> sorted = new SortedList<string, int>();
            sorted.Add("Game1", 1);
            sorted.Add("Game2", 2);
            sorted.Add("Game3", 3);
            sorted.Add("Game4", 4);
            sorted.Add("Game5", 5);

            //
            // Test SortedList with ContainsKey method.
            //

            bool contains1 = sorted.ContainsKey("Game1");
            Console.WriteLine("contains Game1 = " + contains1);

            //
            // Use TryGetValue method.
            //

            int value;
            if (sorted.TryGetValue("Game1", out value))
            {
                Console.WriteLine("Game1 key is = " + value);
            }

            //
            // Use item indexer.|
           //

            Console.WriteLine("Game2 key is = " + sorted["Game2"]);

            //
            // Loop over SortedList data.
            //

            foreach (var pair in sorted)
            {
                Console.WriteLine(pair);
            }

            //
            // Get index of key and then index of value.
            //

            int index1 = sorted.IndexOfKey("Game3");
            Console.WriteLine("index of Game3 (key) = " + index1);|
           int index2 = sorted.IndexOfValue(3);
            Console.WriteLine("index of 3 (value) = " + index2);

            //
            // Display Count property.
            //

            Console.WriteLine("count is = " + sorted.Count);

        }

}

Output

contains java = True
Game1 key is = 1
Game2 key is = 2
[Game1, 1]
[Game2, 2]
[Game3, 3]
[Game4, 4]
[Game5, 5]
index of Game3 (key) = 2
index of 3 (value) = 2
count is = 5


Don't want to miss updates? Please click the below button!

Follow MindStick