The SortedList class represents a collection of key value pair and index.
It is a combination of ArrayList and HashTable . Here, Key value pair and index can be used to access the elements.
If key value pair is used it is like HashTable. If index is used it is like ArrayList.

The SortedList have the following properties:
Property |
Description |
Capacity |
Gets or sets the capacity of the SortedList. |
Count |
Gets the number of elements contained in the SortedList. |
IsFixedSize |
Gets a value indicating whether the SortedList has a fixed size. |
IsReadOnly |
Gets a value indicating whether the SortedList is read-only. |
Item |
Gets and sets the value associated with a specific key in the SortedList. |
Keys |
Gets the keys in the SortedList. |
Values |
Gets the values in the SortedList. |
The SortedList have the following methods:
Sr.No. |
Methods |
1 |
public virtual void Add(object key, object value);
This will adds an element with the specified key and value into the SortedList.
|
2 |
public virtual void Clear();
This will removes all elements from the SortedList.
|
3 |
public virtual bool ContainsKey(object key);
This will determines whether the SortedList contains a specific key.
|
4 |
public virtual bool ContainsValue(object value);
This will determines whether the SortedList contains a specific value.
|
5 |
public virtual object GetByIndex(int index);
It will get the value at the specified index of the SortedList.
|
6 |
public virtual object GetKey(int index);
It will get the key at the specified index of the SortedList.
|
7 |
public virtual IList GetKeyList();
It will get the keys in the SortedList.
|
8 |
public virtual IList GetValueList();
It will get the values in the SortedList.
|
9 |
public virtual int IndexOfKey(object key);
It will returns the zero-based index of the specified key in the SortedList.
|
10 |
public virtual int IndexOfValue(object value);
It will returns the zero-based index of the first occurrence of the specified value in the SortedList.
|
11 |
public virtual void Remove(object key);
This will removes the element with the specified key from the SortedList.
|
12 |
public virtual void RemoveAt(int index);
This will removes the element at the specified index of SortedList.
|
13 |
public virtual void TrimToSize();
It will sets the capacity to the actual number of elements in the SortedList.
|
The SortedList provides to add and access elements in a dynamic manner as we want.
class Program
{
static void Main(string[] args)
{
SortedList sl = new SortedList();
sl.Add("001", "Himanshu Joshi");
sl.Add("002", "Ajay Thakur");
sl.Add("003", "Manoj Negi");
sl.Add("004", "Suresh Sharma");
if (sl.ContainsValue("Himanshu Joshi"))
{
Console.WriteLine("This user name is already in the list");
}
else
{
sl.Add("008", "Himanshu Joshi");
}
// get a collection of the keys.
ICollection key = sl.Keys;
foreach (string k in key)
{
Console.WriteLine(k + ": " + sl[k]);
}
}
}
0 Comment(s)