C # set series: SortedList < TKey,TValue > class

Keywords: C#

sketch:

Namespace:

System.Collection.Generic

Assembly:

System.Collections.dll

SortedList is a mixture of Hashtable and Array. When an element is accessed by its key using the Item indexer attribute, it behaves like a Hashtable. When you use GetByIndex or SetByIndex to access an element by its index, its behavior is similar to Array.

SortedList internally maintains two arrays to store the array in the list; That is, one array is used for keys and another array is used for associated values. Each element is a key / value pair that can be accessed as a DictionaryEntry object. The key cannot be an empty reference (Nothing in Visual Basic), but the value can be.
The Capacity of SortedList is the number of elements that the list can have. As elements are added to the SortedList, Capacity is automatically increased on demand by reallocation. You can reduce Capacity by calling TrimToSize or by explicitly setting the Capacity property.
The elements of SortedList will be sorted according to the specific IComparer implementation (specified when creating SortedList) or the IComparable implementation provided by the key itself. In either case, SortedList does not allow duplicate keys.

The index order is based on the sort order. When you add elements, they are inserted into the SortedList in the correct sort order, and the index is adjusted accordingly. If the element is removed, the index is adjusted accordingly. Therefore, the index of a particular key / value pair may change when an element is added or removed from the SortedList. Due to sorting, it is slower to operate on SortedList than on Hashtable. However, SortedList provides greater flexibility by allowing access to values through associated keys or indexes. Indexes in this collection start from zero.

The foreach statement in C# language (for each in Visual Basic) requires the type of each element in the collection. Since each element of SortedList is a key / value pair, the element type is neither a key type nor a value type. It is a DictionaryEntry type.

Indicates based on correlation   IComparer < T > implements the collection of key / value pairs sorted by keys.

public class SortedList<TKey,TValue> : 
System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>, 
System.Collections.Generic.IDictionary<TKey,TValue>, 
System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey,TValue>>, 
System.Collections.Generic.IReadOnlyCollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>, 
System.Collections.Generic.IReadOnlyDictionary<TKey,TValue>, 
System.Collections.IDictionary

Type parameter:

TKey:

The type of key in the collection.

TValue

The type of value in the collection.

example:  

using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        // Create a new string sorted list using strings
        // keys.
        SortedList<string, string> openWith =
            new SortedList<string, string>();

        // Add some elements to the list. There are no duplicate keys, but some values are duplicate.
        openWith.Add("txt", "notepad.exe");
        openWith.Add("bmp", "paint.exe");
        openWith.Add("dib", "paint.exe");
        openWith.Add("rtf", "wordpad.exe");

        // If the new key is already in the list, the add method throws an exception.
        try
        {
            openWith.Add("txt", "winword.exe");
        }
        catch (ArgumentException)
        {
            Console.WriteLine("An element with Key = \"txt\" already exists.");
        }

        //The item attribute is another name for the indexer, so you can omit its name when accessing an element.

        Console.WriteLine("For key = \"rtf\", value = {0}.",
            openWith["rtf"]);

        // The indexer can be used to change key related values.

        openWith["rtf"] = "winword.exe";
        Console.WriteLine("For key = \"rtf\", value = {0}.",
            openWith["rtf"]);

        // If no key exists, the indexer for that key will add a new key / value pair.

        openWith["doc"] = "winword.exe";

        // If the requested key is not in the list, the indexer throws an exception.
  
        try
        {
            Console.WriteLine("For key = \"tif\", value = {0}.",
                openWith["tif"]);
        }
        catch (KeyNotFoundException)
        {
            Console.WriteLine("Key = \"tif\" is not found.");
        }

        // TryGetValue can be a more effective way to retrieve values when programs often have to try keys that are not in the list.
  
        string value = "";
        if (openWith.TryGetValue("tif", out value))
        {
            Console.WriteLine("For key = \"tif\", value = {0}.", value);
        }
        else
        {
            Console.WriteLine("Key = \"tif\" is not found.");
        }

        // The include key can be used to test the key before inserting it.
        
        if (!openWith.ContainsKey("ht"))
        {
            openWith.Add("ht", "hypertrm.exe");
            Console.WriteLine("Value added for key = \"ht\": {0}",
                openWith["ht"]);
        }

        // When you use the antecedent to enumerate list elements, the elements are retrieved as key Pair objects.
        
        Console.WriteLine();
        foreach( KeyValuePair<string, string> kvp in openWith )
        {
            Console.WriteLine("Key = {0}, Value = {1}",
                kvp.Key, kvp.Value);
        }

        // To get values individually, use the value property.
        IList<string> ilistValues = openWith.Values;

        // The elements of the list strongly type the type specified for the sorted list value.
        
        Console.WriteLine();
        foreach( string s in ilistValues )
        {
            Console.WriteLine("Value = {0}", s);
        }

        // The value property is a valid way to retrieve values by index.
        
        Console.WriteLine("\nIndexed retrieval using the Values " +
            "property: Values[2] = {0}", openWith.Values[2]);

        // To obtain the key individually, use key properties.
        IList<string> ilistKeys = openWith.Keys;

        // The elements of the list strongly type the type specified for the sort list key.
        
        Console.WriteLine();
        foreach( string s in ilistKeys )
        {
            Console.WriteLine("Key = {0}", s);
        }

        // It is an effective method to retrieve the key attributes of the key by index.
        
        Console.WriteLine("\nIndexed retrieval using the Keys " +
            "property: Keys[2] = {0}", openWith.Keys[2]);

        // Use the delete method to delete key / value pairs.
        Console.WriteLine("\nRemove(\"doc\")");
        openWith.Remove("doc");

        if (!openWith.ContainsKey("doc"))
        {
            Console.WriteLine("Key \"doc\" is not found.");
        }
    }
}

/* This code example produces the following output:

An element with Key = "txt" already exists.
For key = "rtf", value = wordpad.exe.
For key = "rtf", value = winword.exe.
Key = "tif" is not found.
Key = "tif" is not found.
Value added for key = "ht": hypertrm.exe

Key = bmp, Value = paint.exe
Key = dib, Value = paint.exe
Key = doc, Value = winword.exe
Key = ht, Value = hypertrm.exe
Key = rtf, Value = winword.exe
Key = txt, Value = notepad.exe

Value = paint.exe
Value = paint.exe
Value = winword.exe
Value = hypertrm.exe
Value = winword.exe
Value = notepad.exe

Indexed retrieval using the Values property: Values[2] = winword.exe

Key = bmp
Key = dib
Key = doc
Key = ht
Key = rtf
Key = txt

Indexed retrieval using the Keys property: Keys[2] = doc

Remove("doc")
Key "doc" is not found.
 */

Constructor:

SortedList<TKey,TValue>()initialization   SortedList<TKey,TValue>   Class, which is empty and has the default initial capacity, and uses the default   IComparer<T>.
SortedList<TKey,TValue>(IComparer<TKey>)initialization   SortedList<TKey,TValue>   Class, which is empty, has the default initial capacity, and uses the specified   IComparer<T>.
SortedList<TKey,TValue>(IDictionary<TKey,TValue>)initialization   SortedList<TKey,TValue>   Class that contains a new instance from the specified   IDictionary<TKey,TValue>   The element copied in has enough capacity to hold the number of copied elements and uses the default   IComparer<T>.
SortedList<TKey,TValue>(IDictionary<TKey,TValue>, IComparer<TKey>)initialization   SortedList<TKey,TValue>   Class that contains a new instance from the specified   IDictionary<TKey,TValue>   The element copied in, which has enough capacity to hold the number of copied elements and uses the specified   IComparer<T>.
SortedList<TKey,TValue>(Int32)initialization   SortedList<TKey,TValue>   Class, which is empty and has the specified initial capacity, and uses the default   IComparer<T>.
SortedList<TKey,TValue>(Int32, IComparer<TKey>)initialization   SortedList<TKey,TValue>   Class, which is empty, has the specified initial capacity, and uses the specified   IComparer<T>.

  Properties:

Capacity

Get or set   SortedList<TKey,TValue>   The number of elements that can be included.

Comparer

Gets the of the sorted list   IComparer<T>.

Count

Get included in   SortedList<TKey,TValue>   Number of key / value pairs in.

Item[TKey]

Gets or sets the value associated with the specified key.

Keys

Gets a containing in sort order   SortedList<TKey,TValue>   A collection of keys in.

Values

Get a containing   SortedList<TKey,TValue>   A collection of values in.

method:  

Add(TKey, TValue)

Adds an element with the specified key and value to the   SortedList<TKey,TValue>   Yes.

Clear()

from   SortedList<TKey,TValue>   Remove all elements from the.

ContainsKey(TKey)

determine   SortedList<TKey,TValue>   Whether to include specific keys.

ContainsValue(TValue)

determine   SortedList<TKey,TValue>   Whether to include specific values.

Equals(Object)

Determines whether the specified object is equal to the current object.

(inherited from)   Object)
GetEnumerator()

Return loop access   SortedList<TKey,TValue>   Enumerator for.

GetHashCode()

As the default hash function.

(inherited from)   Object)
GetType()

Gets the of the current instance   Type.

(inherited from)   Object)
IndexOfKey(TKey)

Throughout   SortedList<TKey,TValue>   Searches for the specified key and returns a zero based index.

IndexOfValue(TValue)

Throughout   SortedList<TKey,TValue>   Searches for the specified value and returns the zero based index of the first occurrence.

MemberwiseClone()

Create current   Object   Shallow copy of.

(inherited from)   Object)
Remove(TKey)

from   SortedList<TKey,TValue>   Removes the element with the specified key from the.

RemoveAt(Int32)

remove   SortedList<TKey,TValue>   The element at the specified index of.

ToString()

Returns a string representing the current object.

(inherited from)   Object)
TrimExcess()

If the number of elements is less than 90% of the current capacity, set the capacity to   SortedList<TKey,TValue>   The actual number of elements in the.

TryGetValue(TKey, TValue)

Gets the value associated with the specified key.

Posted by idnoble on Fri, 29 Oct 2021 01:31:04 -0700