Friday 30 August 2013

SortedList example in c#.

SortedList:-
It is the combination of Arraylist and hashTable . It contains a list of items that can be accessed by using a key or an index. If you access items using an index , it is an arraylist ,and if you are accessing an item using a key , it is a hashtable. The collection of items is always sorted by the key value.

Properties Of  SortedList Class:-
Capacity :- Gets or sets the number of elements that SortedList can contain.
Count :- Gets the number of elements actually contained thr SortedList.
IsFixedSize :- Gets a value indicating whether the SortedList has fixed size.
IsReadOnly :-  Gets a value indicating whether the SortedList has ReadOnly.
Item :- Gets or sets the elements at specified index.
Key :- Gets an ICollection containing the keys in the SortedList.
Value :- Gets an ICollection containing the values in the SortedList.

Methods Of SortedList Class :-
There are various methods in SortedList class for ex. Add(), Clear(),Remove() etc. I have explained all methods in below example of sortedlist.

Example:-
using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.Data;

namespace CollectionExample
{
    class Program
    {
//SortedList Example-------------------------------------------------------------------------
            Console.WriteLine("-------------SortedList table Example---------------");
            SortedList sl = new SortedList();

            sl.Add("1", "Sushil");
            sl.Add("2", "Kumar");
            sl.Add("3", "Sanjay");
            sl.Add("4", "Muthu");
            sl.Add("5", "Ashu");

            sl.Remove("1");

            if (sl.ContainsValue("Mantra"))
            {
                Console.WriteLine("This name already exist in SortedList.");
            }
            else
            {
                sl.Add("6", "Mantra");
            }

            ICollection key = sl.Keys;// to get collection of key

            foreach (string s in key)
            {
                Console.WriteLine(s + " : " + sl[s]);
            }

            Console.ReadKey();
      }
   }
}

Output:-
-------------SortedList table Example---------------
2 : Kumar
3 : Sanjay
4 : Muthu
5 : Ashu

6 : Mantra

No comments:

Post a Comment

Note: only a member of this blog may post a comment.