1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Collection classes in .NET

Discussion in 'C#' started by MinalS, Mar 22, 2015.

  1. MinalS

    MinalS New Member

    Joined:
    Jul 8, 2014
    Messages:
    138
    Likes Received:
    30
    Trophy Points:
    0
    Collections classes like ArrayList, Hashtable, Stack, and Queue are used. The various concepts of generics and its classes can be explored in this article.

    Collection classes in .NET

    .NET frame work provides user with different collection classes. They are present in System.Collections namespace. The classes create collections of object class, the base class for all data types.

    The list of collections classes defined in the namespace are as mentioned below:
    1. ArrayList
    2. HashTable
    3. SortedList
    4. Stack
    5. Queue

    1. ArrayList



    In an array, the size is fixed during the declaration of array. User cannot add items at any location in an array. The ArrayList class provides user with this advantage. ArrayList class allows user to store and manage elements. The elements can be added and removed from specific position, the array can be resized automatically.

    Properties in ArrayList
    1. Count: It access the number of elements in the ArrayList
    2. IsFixedSize: It accesses the value to specify whether the ArrayList object has a fixed size.
    3. Item: It accesses or sets the element at the specified item.
    4. IsReadOnly: It accesses the value specify whether the object is read only
    Methods in ArrayList
    1. Clear(): It removes all the items from the ArrayList object
    2. Add(): It adds an item at the end of the object
    3. Contains(): It returns value true if the item is present in the list
    4. IndexOf(): It returns the zero based index for the first occurrence of the specified item
    5. RemoveAt(): It removes the item from the specified index of the object
    Consider an example to demonstrate the arraylist in an application.
    Code:
    public partial class Form1: Form
    {
        private ArrayList a1;
        public Form1
        {
            InitializeComponent();
        }
        private void LoadList()
        {
            listBox1.Items.Clear();
            for ( int i=0;i<a1.Count;i++)
            {
                listbox1.Items.Add(a[i]);
            }
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            button2.Enabled=false;
        }
        private void button1_Click(object sender, EentArgs e)
        {
            a1 = new ArrayList(5);
            a1.Add("MA");
            a1.Add("MBA");
            a1.Add("MCA");
            a1.Add("BCA");
            a1.Add("BCom");
            LoadList();
            button1.Enabled=true;
            button2.Enabled=true;
        }
        private void button2_Click(object sender, EventArgs e)
        {
            if( a1.Count > 0)
            {
                a1.Sort();
                LoadList();
            }
        }
    }
    
    The output for the above code is as shown below:

    [​IMG]

    When the sort button is clicked, the output is as shown below:

    [​IMG]

    2.HashTable



    The HashTable helps user access item by a key. Every item is present in the Key/Value pair. The items can be accessed using the key. Key must have unique value. The value is the one stored in an array. The keys are short strings or integers.

    Properties in HashTable
    1. Count: It retrieves the key value pairs present in the table
    2. IsFixedSize: It retrieves the value specifying the object is of fixed size
    3. Keys: It retrieves collection of keys in the object
    4. Values: It accesses the collection of values in the object
    Methods in HashTable
    1. Clone(): It creates a copy of the hashtable object
    2. ContainsKey(): It returns true if the specified key in the hash table
    3. CopyTo(): It copies the hashtable object items into one dimensional array.
    4. GetObjectData(): It implements the ISerializable interface and returns data useful for serialization of the interface
    5. Remove(): It removes an item with the specified key from the table object
    Consider an example to demonstrate the hashtable.
    Code:
    public partial class Form1: Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        Hashtable h1 = new HshTable(5);
        private void LoadHashTable()
        {
            listView1.Items.Clear();
            foreach(object obj in ht.Keys)
            {
                ListViewItem l1 = ListView1.Items.Add(obj.ToString());
                l1.SubItems.Add(ht[obj]).ToString();
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            ht.Add(10, "Pen");
            ht.Add(20, "Books");
            ht.Add(30, "Laptop");
            ht.Add(40, "Books");
            ht.Add(50, "Letters");
            LoadHashTable();
            button1.Enabled=true;
        }
    }
    
    The output for the code is:

    [​IMG]

    3. SortedList Class



    The class is a combination of Array and HashTable class. It has list of items that can be accessed using index or key. The SortedList object acts an ArrayList object where user can access items through keys. The collection classes are always sorted according to keys in sortedlist class.

    The items in the class are always sorted in ordered according to the values of their keys.

    Properties of SortedList Class
    1. Capacity: It access or sets the number of elements that the list object can hold
    2. IsSynchronized: It accesses the value specifying to access the list object is synchrononized.
    3. Item: It accesses or sets the value with the specific key in the list object
    4. Count: It retrieves the number of elements present in the list object
    5. SyncRoot: It accesses the object used to synchronize the list object
    Methods of SortedList Class
    1. SetByIndex(): It sets the value to the specified index of the object
    2. TrimToSize(): It is used to set the capacity of the list object to the actual number of items in the list object
    3. GetByIndex(): It is used to retrieve the value at the specified object
    4. IndexOfKey(): it is used to perform the operations for the specific key and zero base index is returned.
    5. CopyTo(): It copies the object items to one directional array at the specific index.

    4. Stack Class



    The Stack class uses the Last In First Out order. The object added at the top of the stack is processed first. When an item is added to the stack, it is known as pushing the item to the stack. When the item is removed from the stack, it is known as popping.

    Properties of Stack Class
    1. IsSynchronized: It accesses the value specifying to access the stack object which is synchronized.
    2. SyncRoot: It accesses the object used to synchronize the Stack object
    3. Count: It retrieves the number of elements available in the object.
    Methods of Stack Class
    1. Peek(): It returns the item at the top of the object without removing.
    2. Pop(): It removes and returns the item at the top of the stack object
    3. Push(): It adds the item at the top of the stack object
    4. ToArray(): It copies the object to the new array
    5. GetEnumerator(): It returns the IEnumerator object for the stack object
    The code snippet to demonstrate the stack class is as shown below:
    Code:
    public Form Form1
    {
        InitializeComponent();
    }
    private Stack s;
    private void Form1_Load( object sender, EventArgs e)
    {
    }
    private void button1_Click(object sender, EventArgs e)
    {
        s= new Stack(5);
        s.Push("New");
        s.Push("Best");
        s.Push("Good");
        s.Push("Old");
        s.Push("Gold");
        Loads();
        button2.Enabled=true;
        button3.Enabled=true;
    }
    private void button2_Click(object sender, EventArgs e)
    {
        Loads();
    }
    
    private void Loads()
    {
        listBox1.Items.Clear();
        object[] objarr = s.ToArray();
        for(int i=0;i<s.count;i++)
        listbox1.Items.Add(objarr[i]);
    }
    private void button3Click(object sender, EventArgs e)
    {
        MessageBox.Show(s.Pop.ToString(), "Item is Popped");
        Loads();
    }
    
    The output for the code is as shown below:

    [​IMG]

    [​IMG]

    5. Queue Class



    The Queue class uses the First In First Out order. It processes the order in which user ahs created the queue. The method which adds the item is known as Enqueue and removed is known as Dequeue.

    Properties of Queue Class
    1. IsSynchronized: It accesses the value specifying to access the queue object which is synchronized.
    2. SyncRoot: It accesses the object used to synchronize the Queue object
    3. Count: It retrieves the number of elements available in the object.
    Methods of Queue Class
    1. Dequeue(): It removes and returns item at the beginning of the queue object
    2. Enqueue(): It adds an item at the end of the object
    3. Peek(): It returns the item at the queue beginning without any removal
    4. TrimToSize(): It sets the capacity of the object to the number of items stored in the queue
    The code snippet to demonstrate the queue is as shown below:
    Code:
    public Form Form1
    {
        InitializeComponent();
    }
    private Queue q;
    private void Form1_Load( object sender, EventArgs e)
    {
    }
    private void button1_Click(object sender, EventArgs e)
    {
        q=new Queue(5);
        q.Enqueue("Blue");
        q.Enqueue("Red");
        q.Enqueue("Yellow");
        q.Enqueue("Pink");
        q.Enqueue("Black"); 
        Loads();
        button2.Enabled=true;
        button3.Enabled=true;
    }
    private void button2_Click(object sender, EventArgs e)
    {
        Loads();
    }
    
    private void Loads()
    {
        listBox1.Items.Clear();
        object[] objarr = q.ToArray();
        for(int i=0;i<q.count;i++)
        listbox1.Items.Add(objarr[i]);
    }
    private void button3Click(object sender, EventArgs e)
    {
        MessageBox.Show(q.Dequeue.ToString(), "Item is dequeued");
        Loads();
    }
    
    The output for the above code is as shown below:

    [​IMG]

    [​IMG]
     

Share This Page