C# Sorted List(Non generic)
Non-generic SortedList is defined under System.Collections namespace
Properties of Sorted List
- Capacity: Gets or sets the number of elements that the SortedList instance can store.
- Count: Gets the number of elements actually 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 or sets the element at the specified key in the SortedList.
- Keys: Get list of keys of SortedList.
- Values: Get list of values in SortedList.
Method of Sorted List
1) Add(object key, object value): Add key-value pairs into SortedList.
Key cannot be null but value can be null. Also, datatype of all keys must be same, so that it can compare otherwise it will throw runtime exception.Non-generic SortedList collection can contain key and value of any data type. So values must be cast to the appropriate data type otherwise it will give compile-time error.
Example:
class CollectionExamples
{
static void Main(string[] args)
{
SortedList sl = new SortedList();
sl.Add(3, "Three");
sl.Add(1, "One");
sl.Add(2, "Two");
sl.Add(4, null);
foreach (var item in sl.Keys)
{
Console.WriteLine("Sorted List {0}", item);
}
Console.ReadLine();
}
}
Output:
Sorted List 1
Sorted List 2
Sorted List 3
Sorted List 4
2) Remove(object key): Removes element with the specified key.
3) RemoveAt(int index): Removes element at the specified index.
Example
static void Main(string[] args)
{
SortedList sl = new SortedList();
sl.Add(3, "Three");
sl.Add(1, "One");
sl.Add(2, "Two");
sl.Add(4, null);
sl.Remove(3);//Remove element whose key is two
sl.RemoveAt(0);//Remove element whose index is 1
foreach (DictionaryEntry de in sl)
{
Console.WriteLine("Sorted List {0}", de.Key);
}
Console.ReadLine();
}
Output:
Sorted List 2
Sorted List 4
4)Contains: This method is used to check whether a SortedList object contains a specific key.
5)ContainsKey: This method is used to check whether a SortedList object contains a specific key.
6)ContainsValue: This method is used to check whether a SortedList object contains a specific value.
Example:
static void Main(string[] args)
{
SortedList sl = new SortedList();
sl.Add(3, "Three");
sl.Add(1, "One");
sl.Add(2, "Two");
sl.Add(4, null);
Console.WriteLine("Contains {0}",sl.Contains(3)); // Return true if given key is found.
Console.WriteLine("Contains Key {0}", sl.ContainsKey(3));// Return true if given key is found.
Console.WriteLine("Contains value {0}", sl.ContainsValue("Three"));//Return true if given value found.
Console.ReadLine();
}
GetByIndex(int index) : Returns the value by index stored in internal array
GetKey(int index): Returns the key stored at specified index in internal array
IndexOfKey(object key): Returns an index of specified key stored in internal array
IndexOfValue(object value) : Returns an index of specified value stored in internal array
carry on, don’t stop !!
ReplyDelete