We are providing online training of realtime Live project on Asp.Net MVC with Angular and Web API. For more information click here. If you have any query then drop the messase in CONTACT FORM

Tuesday, July 14, 2015

Collections And Generic Collections

Collections

A Collection is also similar to Array which is dynamic in size i.e. the size of a collection increases as you add new items to the collection where as the arrays are fixed length which can only a Pre-defined number of Rows.

Collections are capable of storing dissimilar type of value in them where as array can store similar type of values only.

In the Data structure we have to using in our traditional languages like C, C++ i.e. Stack, Queue, Linked List, Sorted List etc .Comes under a category of collections only.

.NET provides us number of classes implemented as collections under the namespace 'System.Collections' like Stack,Queue,Linked List, SortedtList, ArrayList,Hastable etc. which can be directly consumed.

Stack:

It is a DataSource that manages the data on a principle 'Fist In Last Out' (or) 'Last In First Out'. To add and remove data from the stack we have been provided with methods like 'Push’,’ Pop' directly. So we can create object of this class and straight away consume the stack without implementation.

* Open a new project of type 'Console' application and name it as 'CollPrjoect', write the following code under the default class 'Program'

class Program
        {
            static void Main(string[] args)
            {
                Stack s = new Stack();
                s.Push(10); s.Push("Hello");
                s.Push(true); s.Push('a');
                s.Push(3.14f); s.Push(78.98);
                foreach (object obj in s)
                    Console.Write(obj + " ");
                Console.WriteLine();
                Console.WriteLine(s.Pop());
                foreach (object obj in s)
                    Console.Write(obj + " ");
                Console.WriteLine();
                Console.WriteLine(s.Peek());
                 foreach (object obj in s)
                       Console.Write(obj + " ");

                Console.WriteLine();
                Console.WriteLine(s.Count);
                s.Clear();
                Console.WriteLine(s.Count);
                Console.ReadLine();
            }

        }

  •  'Push' method adds value from the bottom of the 'Stack'.
  •  'Pop' method returns and remove the topmost value of the Stack
  •  'Peek' method returns the topmost value of the Stack without removing it.
  •  'Clear' method clears all the values of the Stack.
  •  'Count' is a property that tells the number of items in the Stack.

ArrayList

It is a collection class that behaves similar to an Array that stores you the value in the form of a Sequential order and also we can access any value of an ArrayList using its Index Position. The main difference between Array & ArrayList is Array is static in size which can store similar types of values only whereas ArrayList stores any number of dissimilar types of values.

*Add a class "Class1.cs" and write the following.

  class Class1
        {
             static void Main()
            {
                ArrayList al = new ArrayList();
                Console.WriteLine("Initial Capacity:" + al.Capacity);
                al.Add(100);

                Console.WriteLine("Capacity after adding 1st item:" + al.Capacity);
                al.Add(3.14f); al.Add(22.32m); al.Add(true);

                Console.WriteLine("Capacity after adding 4th item:" + al.Capacity);
                al.Add(false);

                Console.WriteLine("Capacity after adding 5th item:" + al.Capacity);
                al.Add("Hello");
                foreach (object obj in al)
                    Console.Write(obj + " ");

                Console.WriteLine();
                Console.ReadLine();

            }
        }

Note: - When we want to transfer a set of values from one class to other we transfer them by storing the values under an ArrayList because this will be easier for transporting multiple values at a time.

  •  Every collection class has the capability of incrementing its capacity dynamically whenever the requirement comes.
  •  A collection class object can be created making use of 3 different constructors.

1) A default constructor that initializes the class within the initial capacity of '0' and that becomes 4 after adding the first element under the collection from now whenever there is a requirement the capacity doubles.

2) We can also create an object of collection class by specifying the initial capacity using the constructor. Now also whenever the requirement comes the capacity doubles.

3) We can create a collection by passing an existing collection as a parameter to the constructor which will copy the values of old collection to the new collection which will be taken as an initial capacity. Now also when the requirement comes the capacity doubles.

HashTable:

It is also a collection class that can store your values in the form of 'Key-Value Pairs'.

An Array or a ArrayList also stores values in the form of 'Key-Value Pairs' only where the Key is the 'Index' which is Pre-defined that starts from '0' only whereas 'Hashtable' the provision of specifying our own keys to the values where a 'Key' also can be of any type.

*Add a class 'Class2.cs' and write the following.

   class Class2
        {
            static void Main()
            {
                Hashtable ht = new Hashtable();
                ht.Add("Eno", 101);
                ht.Add("Ename", "Mithilesh");
                ht.Add("Job", "Manager");
                ht.Add("Salary", 50000);
                ht.Add("Dname", "Software");
                foreach (object obj in ht.Keys)
                    Console.WriteLine(obj + ":\t" + ht[obj]);

                Console.ReadLine();
            }

        }

Note: - Hashtable class is also used for transporting the data from one class to another in a descriptive fashion that is each value can be described by its key.

Generic Collections


These are an extension to the 'Collections' we have discussed earlier that can store only a specified type of values. But traditional Collections can store any type of value.

While creating an object of a Generic collection class we can explicitly specify what type of values we want to store under the collection.

All traditional collection classes are re-designed and provided as Generic collections under the namespace 'System.Collections.Generic'

Collections Generic Collection
Stack Stack<T>

Queue Queue<T>

LinkedList LinkedList<T>

SortedList SortedList<T>

ArrayList List<T>

Hashtable Dictionary<T>

We create the object of Generic collection as following.

Stack<int> si=new Stack<int> ();

Stack<string> ss=new Stack<string> ();

In place of 'type' we can also specify a 'class' type also that is if we have a class 'customer' and want to store objects of class customers we can declare a collection as follows.

Stack<Customer> sc=new Stack<Customer> ();

*Add a class "Class3.cs" and write the following code.


class Class3
    {
        static void Main()
        {
            List<int> li = new List<int>();
            li.Add(10); li.Add(20); li.Add(30);
            li.Add(40); li.Add(50); li.Add(60);
            foreach (int i in li)
                Console.Write(i + " ");
            Console.WriteLine();
            for (int i = 0; i < li.Count; i++)
                Console.Write(li[i] + " ");
            Console.ReadLine();

        }

    }

Collection Initializers

Prior to C#3.0, we cannot initialize a collection at the time of its declaration just like we can do it in the case of Array, but from 3.0 we are also given with the option to initialize a collection at the time of its declaration as follows.

List<int> li = new List<int>() { 10, 20, 30, 40, 50, 60 };

    Before 3.0

int[] arr = { 10, 20, 30, 40, 50, 60 };

    List<int> li = new List<int>();

    li.AddRange(arr);

* Add a class "Class4.cs" and write the following code

    class Class4
{
        static void Main()
        {
            List<int> li = new List<int>() { 23, 67, 10, 91, 83, 43, 5, 38, 27, 53, 49, 96, 18, 9, 24, 36, 72, 83 };
            List<int> coll = new List<int>();
            foreach (int i in li)
            {
                if (i > 40)
                    coll.Add(i);
            }
            coll.Sort();
            coll.Reverse();
            foreach (int i in coll)
                Console.Write(i + " ");
            Console.ReadLine();
        }

    }

No comments: