Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C# SortedList

C# SortedList

C# Collection C# Collections

In C#, a sorted list (SortedList) is a collection that automatically sorts by key. It stores data as key/value pairs and automatically sorts by key order (ascending) when items are added or updated.

The SortedList class represents a series of key => value pairs sorted by key; these pairs can be accessed by key and by index.

A SortedList is a combination of an array and a Hashtable. It contains a list that can be accessed by key or by index. If you access items by index, it is like an ArrayList; if you access items by key, it is like a Hashtable. The items in the collection are always sorted by key.

SortedList has two versions:

  1. Non-generic SortedList(System.Collections.SortedList)
  2. Generics SortedList(System.Collections.Generic.SortedList)

** Features:**

SortedList Class Methods and Properties

The following table lists the SortedList Some commonly used members of the class property:

Attribute name Type Description
Count int Gets the number of key/value pairs in the sorted list.
Capacity int Gets or sets the capacity of the sorted list.
Comparer IComparer or IComparer Gets the comparer used to sort the keys.
IsReadOnly bool Indicates whether the sorted list is read-only.
IsFixedSize bool Indicates whether the sorted list has a fixed size (always false)。
Keys ICollection or IList Gets all keys in the sorted list.
Values ICollection or IList Gets all values in the sorted list.

The following table lists the SortedList Some commonly used members of the class Method:

Method Name Return Type Description
Adding and Removing
Add(TKey key, TValue value) void Adds the specified key/value pair to the sorted list.
Remove(TKey key) bool Removes the element with the specified key from the sorted list.
RemoveAt(int index) void Removes the key/value pair at the specified index in the sorted list.
Clear() void Removes all elements from the sorted list.
Searching and Access
ContainsKey(TKey key) bool Determines whether the sorted list contains the specified key.
ContainsValue(TValue value) bool Determines whether the sorted list contains the specified value.
IndexOfKey(TKey key) int Returns the index of the specified key.
IndexOfValue(TValue value) int Returns the index of the specified value.
TryGetValue(TKey key, out TValue value) bool Gets the value associated with the specified key, returning it if it exists, or true。
Copying and Enumeration
CopyTo(Array array, int index) void Copies the elements of the sorted list to an array, starting at the specified index.
GetEnumerator() IEnumerator Returns an enumerator that iterates through the elements of the sorted list.

Example

The following example demonstrates the concept of a sorted list (SortedList).

** Non-generic version operations:**

Example

using

System

;

using

System.Collections

;

namespace

CollectionsApplication

{

   

class

Program

   

{

     

static

void

Main

(

string

[

]

args

)

     

{

         SortedList sl

=

new

SortedList

(

)

;

         sl

.

Add

(

"001"

,

"Zara Ali"

)

;

         sl

.

Add

(

"002"

,

"Abida Rehman"

)

;

         sl

.

Add

(

"003"

,

"Joe Holzner"

)

;

         sl

.

Add

(

"004"

,

"Mausam Benazir Nur"

)

;

         sl

.

Add

(

"005"

,

"M. Amlan"

)

;

         sl

.

Add

(

"006"

,

"M. Arif"

)

;

         sl

.

Add

(

"007"

,

"Ritesh Saikia"

)

;

         

if

(

sl

.

ContainsValue

(

"Nuha Ali"

)

)

         

{

            Console

.

WriteLine

(

"This student name is already in the list"

)

;

         

}

         

else

         

{

            sl

.

Add

(

"008"

,

"Nuha Ali"

)

;

         

}

         

// Get the collection of keys

         ICollection key

=

sl

.

Keys

;

         

foreach

(

string

k

in

key

)

         

{

            Console

.

WriteLine

(

k

": "

sl

[

k

]

)

;

         

}

     

}

   

}

}

When the code above is compiled and executed, it produces the following result:



001: Zara Ali

002: Abida Rehman

003: Joe Holzner

004: Mausam Banazir Nur

005: M. Amlan 

006: M. Arif

007: Ritesh Saikia

008: Nuha Ali

** Generic version:**

Example

using

System

;

using

System.Collections.Generic

;

class

Program

{

   

static

void

Main

(

)

   

{

       

// Create a generic SortedList

        SortedList

<

int

,

string

sortedList

=

new

SortedList

<

int

,

string

(

)

;

       

// Add key/value pairs

        sortedList

.

Add

(

2

,

"Banana"

)

;

        sortedList

.

Add

(

1

,

"Apple"

)

;

        sortedList

.

Add

(

3

,

"Cherry"

)

;

       

// Automatically sorted by key

        Console

.

WriteLine

(

"SortedList contents:"

)

;

       

foreach

(

var

kvp

in

sortedList

)

       

{

            Console

.

WriteLine

(

$

"Key: {kvp.Key}, Value: {kvp.Value}"

)

;

       

}

       

// Search and access

        Console

.

WriteLine

(

$

"\nValue for key 2: {sortedList[2]}"

)

;

// Output: Banana

       

// Delete elements

        sortedList

.

Remove

(

1

)

;

        Console

.

WriteLine

(

"\nAfter removing key 1:"

)

;

       

foreach

(

var

kvp

in

sortedList

)

       

{

            Console

.

WriteLine

(

$

"Key: {kvp.Key}, Value: {kvp.Value}"

)

;

       

}

       

// Check keys and values

        Console

.

WriteLine

(

$

"\nContains key 3: {sortedList.ContainsKey(3)}"

)

;

// Output: True

        Console

.

WriteLine

(

$

"Contains value 'Apple': {sortedList.ContainsValue("

Apple

")}"

)

;

// Output: False

   

}

}

C# Collection C# Collections