User Name:


User Email:




This information will only be saved for the purposes of communicating with those who have provided this information voluntarily regarding our services.We will never sell your name or email address to anyone.
© 2018 - First Crazy Developer (Abhishek Kumar)
  

crazydeveloper Use and Importance of Collection in C#

Hi, today I'd like to discuss about "Collection in C#". In order to understand the importance of Collection and why we need that in our programming language, we'll need to look back into our time machine and should start journey from .Net Framework 2.0 to .Net Framework 4.5. It's a long journey where we walked with C# and learned lots of new code and concepts after each and every requirement in our projects and products. Now we feel that with C# feel like family.

Here we will discuss C# 2.0 when Collection introduced for coder & developer.

The first question come into our mind - Why we need Collection?

In many times we want to work with group of related objects. Before Collection we used Array for the same. If we can work with group of objects with array then why we need "Collection"?

First we create a sample application with the name "CollectionSampleApp". Now let’s take a look at the following code:


  1. namespace CollectionSampleApp
  2. {
  3. public class Program
  4. {
  5. static void Main(string[] args)
  6. {
  7. int[] numCollection = new int[5];
  8. for(int i=0;i<numCollection.Length;i++)
  9. {
  10. numCollection[i] = i;
  11. }
  12. }
  13. }
  14. }


In the above code we can see array are useful for working with strongly type data with fixed length. Imagine in our application we defined an array with 100 length but in run time we used only 50 length so rest 50 are unused here. In this scenario either we defined enough length so we don't face IndexOutOfRangeException but in this case we face wastage of memory or we can use Arrary.Resize(ref numCollection, newLength). But internally "what happen when we resize the array in our application?"

"Internally, the single call to Array.Resize above runs through an algorithm that determines that the array needs to be smaller. So it copies the referenced array to a new array, and then changes the reference."

These are disadvantage when we work with array in our application. When we find the solution of this scenario we get Collection in C#. Collections provide us more flexible way to work with groups of objects. Unlike arrays, the group of objects we work with can grow and shrink dynamically as the needs of the application change. Collection give us more control over groups of objects for iteration and manipulation.

In simple word we can say- "Array are useful for fixed length with strongly type data but Collection give you power to grow and shrink dynamically without any data type limitation".

After the above discussion I hope we understood what Collection is and why we need that in our application. Now move a step ahead with discussion, but first, here’s an important question:

What are the different types of collections in .NET Framework?

Any idea, any guess guys most of experienced developer have answer but still beginner will be wondering about that. Don't worry below we will start discuss about that.

In .Net Framework Collection are divided into four categories. What are they?

Now let’s take a look at the following discussion:

    1. Indexed based.
    2. Key Value Pair.
    3. Prioritized Collection.
    4. Specialized Collection.


Look at the below image to better understand:




In the above image, We  categorised the Collection into four type then they also divided as per their types.

Let’s begin our discussion with Indexed based Collection with some example.


In the above image we can see we have some data and we will store these data with Indexed based Collection.

Now let's take a look at the following code.

  1. namespace CollectionSampleApp
  2. {
  3. public class Program
  4. {
  5. static void Main(string[] args)
  6. {
  7. ArrayList obj = new ArrayList();
  8. for(int i=0;i<6;i++)
  9. {
  10. obj.Add(Console.ReadLine());
  11. }
  12. Console.WriteLine("***************** Final Output *************************");
  13. for (int i = 0; i < obj.Count; i++)
  14. {
  15. Console.WriteLine(obj[i].ToString());
  16. }
  17. Console.ReadKey();
  18. }
  19. }
  20. }


In the above code we can see, we defined a variable named "objArrayList" of ArrayList data type. Then we iterate through for loop and gets input from user and added into ArrayList. After getting all inputs again we iterate loop and print that values. Here we can see that the length of Collection increase dynamically and access data on Index base.

Look at the following image:





Now move ahead and start with Key Value Pair Collection with some example.


  1. namespace CollectionSampleApp
  2. {
  3. public class Program
  4. {
  5. static void Main(string[] args)
  6. {
  7. Hashtable hashtableObj = new Hashtable();
  8. hashtableObj[7] = "First Crazy Developer";
  9. hashtableObj[16] = "Abhishek Kumar";
  10. hashtableObj[25] = "Crazy Developer";
  11. foreach (DictionaryEntry entry in hashtableObj)
  12. {
  13. Console.WriteLine("{0}, {1}", entry.Key, entry.Value);
  14. }
  15. }
  16. }
  17. }


In the above code we can see, we defined a variable named "hashtableObj" of Hashtable data type. Then we set values into hash table object with key value pairs. We can see first we set value "First Crazy Developer" with key "7" in next line set "Abhishek Kumar" with key "16" in next line set "Crazy Developer" with key "25". Take a closely look in the above example, after set the all values we iterate that hashtable and print value with key.

Look at the following image:


There are one more class "SortedList", which used for store data in key value pair in C#.

Look at the following code:


  1. namespace CollectionSampleApp
  2. {
  3. public class Program
  4. {
  5. static void Main(string[] args)
  6. {
  7. SortedList sortedListObj = new SortedList();
  8. sortedListObj[7] = "First Crazy Developer";
  9. sortedListObj[16] = "Abhishek Kumar";
  10. sortedListObj[25] = "Crazy Developer";
  11. foreach (DictionaryEntry entry in sortedListObj)
  12. {
  13. Console.WriteLine("{0}, {1}", entry.Key, entry.Value);
  14. }
  15. }
  16. }
  17. }



Again in the above code we can see, we defined a variable named "sortedListObj" of SortedList data type. Then I just used above same code here to store and display data. If we go through both code we found that code to use both are same. If both are same then here’s an important question:

What is difference between "Hashtable and SortedList?"

The difference between them is that, in the SortedList, the key/value pairs are sorted by key and, since they have a definite order, you can access them by index as well as by key.

In the HashTable, the key/value pairs are not sorted and we can only access them by key. Because Hashtable represents a collection of key/value pairs that are organized based on the hash code of the key, and when an element is added to the Hashtable its stored based on the hash code of the key, and the elements don't preserves the order based in their insertion to the Hashtable's "bag".

This means that random insertions for the SortedList are relatively slow because it needs to be resorted after each insertion. On the other hand, in some applications it is useful to be able to iterate through the keys in sorted order.

After discussion of Key Value pair, now move ahead to start discussion of "Prioritized Collection" with some example: When we talk about "Prioritized Collection" in .Net Framework there are two types collection support:

a) Stacks
b) Queues


Stacks: Stack operates on Last in First out (LIFO) principle.

Queues: Queue operates on First in First Out (FIFO) principle.

In the above two statements we can understand the basic concepts of "Prioritized Collection" with Stacks & Queues. Here let me ask you "what we understood?"

When we remove any item from Stacks, the item added last is removed first. In the case of Queues behaviour is vice versa means, the item added first removed first.

Look at the following statements for better understanding about "Stacks & Queues":

Queue:-


1) A Queue is a collection where elements are processed in "First in First Out ".
2) The items that is put first in the Queue is read first.
3) Enqueue() method adds an item to the end of the Queue.
4) Dequeue() method reads and removes an item from the head of the Queue.
5) Peek() method reads an item from the head of the Queue but does not remove an item.

Stack:-


1) Stack is a collection where elements are processed in "Last in First Out ":.
2) The items that is added last to the Stack is read first.
3) Push() method adds an item to the Top of the Queue.
4) Pop() method returns an item from the Top of the Stack.
5) Peek() method returns an item from the Top of the Stack but does not remove an item.
6) Structs are Value Type
7) Structs stored in Stack.It does not support Inheritance

Now let’s take a look at the following code:

  1. namespace CollectionSampleApp
  2. {
  3. public class Program
  4. {
  5. static void Main(string[] args)
  6. {
  7. //Queue object declaration
  8. Queue QueueObj = new Queue();
  9. //Store data in Queue
  10. for (int i = 0; i < 5; i++)
  11. {
  12. QueueObj.Enqueue(i + 1); // store data in Queue
  13. }
  14. DisplayElementsQueue("Display the Queue Elements",QueueObj);
  15. //Get the object at the beginning of the Queue
  16. Console.WriteLine("First data: {0}", QueueObj.Peek()); // get first element
  17. //Remove the First three data from the Queue. Note: The first three entries added will be removed
  18. Console.WriteLine("First Removed Element: {0}", QueueObj.Dequeue()); // remove first element
  19. Console.WriteLine("Second Removed Element: {0}", QueueObj.Dequeue()); // remove first element after previous removed
  20. Console.WriteLine("Second Removed Element: {0}", QueueObj.Dequeue()); // remove first element after previous removed
  21. DisplayElementsQueue("Display the Queue Elements after removed", QueueObj);
  22. }
  23. public static void DisplayElementsQueue(string message,Queue tempObj)
  24. {
  25. // Display data from Queue
  26. Console.WriteLine("********************************** " + message + " **********************************");
  27. foreach (int item in tempObj)
  28. {
  29. Console.Write(item + ", ");
  30. }
  31. Console.WriteLine("*********************************);
  32. }
  33. }
  34. }

In the above code we can see there is a complete sample code of Queue to add, get and remove elements. When we execute the above code get the following output.


I hope in the above discussion we understood the concepts of Queue. Now move ahead for Stack and look at the following code:


  1. namespace CollectionSampleApp
  2. {
  3. public class Program
  4. {
  5. static void Main(string[] args)
  6. {
  7. //Stack object declaration
  8. Stack stackObj = new Stack();
  9. //Store data in Stack
  10. for (int i = 0; i < 5; i++)
  11. {
  12. stackObj.Push(i + 1); // store data in Stack
  13. }
  14. DisplayElementsStacks("Display the Stack Elements", stackObj);
  15. //Get the object at the beginning of the Stack
  16. Console.WriteLine("First data: {0}", stackObj.Peek()); // get first element
  17. //Remove the First three data from the Stack. Note: The last three entries added will be removed
  18. Console.WriteLine("First Removed Element: {0}", stackObj.Pop()); // remove first element
  19. Console.WriteLine("Second Removed Element: {0}", stackObj.Pop()); // remove first element after previous removed
  20. Console.WriteLine("Third Removed Element: {0}", stackObj.Pop()); // remove first element after previous removed
  21. DisplayElementsStacks("Display the Stack Elements after removed", stackObj);
  22. Console.ReadLine();
  23. }
  24. public static void DisplayElementsStacks(string message,Stack tempObj)
  25. {
  26. // Display data from Stack
  27. Console.WriteLine("********************************** " + message + " **********************************");
  28. foreach (int item in tempObj)
  29. {
  30. Console.Write(item + ", ");
  31. }
  32. Console.WriteLine("");
  33. Console.WriteLine("***************************************");
  34. }
  35. }
  36. }


In the above code we can see there is a complete sample code of Stack to add, get and remove elements. When we execute the above code get the following output.



Now after all above the discussion we came at last steps of Collection and that is Specialized Collection. It is very specific collections which are meant for very specific purpose like hybrid dictionary that start as List and become Hashtable. We need to include "System.Collections.Specialized;" in our code file to use this collection. HybridDictionary attempts to optimize Hashtable. It implements a Linked List and Hash Table data structure, switching over to the second from the first when the number of elements increases past a certain threshold. It will internally use a ListDictionary while the count is less than or equal to 10 and only when the list becomes larger does it convert to using a Hashtable. The HybridDictionary is best used in situations where some lists are small and others are very large or you just aren’t sure how big a list might eventually grow. The generic equivalent of Hybrid Dictionary Collection is the Dictionary<>.

Look at the following code:

  1. using System;
  2. using System.Collections;
  3. using System.Collections.Specialized;
  4. using System.Text;
  5. using System.Threading;
  6. namespace CollectionSampleApp
  7. {
  8. public class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12. // Declare and Get & Set HybridDictionary
  13. HybridDictionary hybridObj = GetSampleHybridDictionary();
  14. // Get values from HybridDictionary
  15. int tempValue1 = (int)hybridObj["cat"];
  16. object tempValue2 = hybridObj["notfound"];
  17. object tempValue3 = hybridObj["dog"];
  18. int tempCount = hybridObj.Count;
  19. // Now Display all getting values
  20. Console.WriteLine(tempValue1);
  21. Console.WriteLine(tempValue2 == null);
  22. Console.WriteLine(tempValue3);
  23. Console.WriteLine(tempCount);
  24. // Here Enumerate HybridDictionary
  25. foreach (DictionaryEntry tempEntry in hybridObj)
  26. {
  27. Console.Write(tempEntry.Key);
  28. Console.Write(": ");
  29. Console.WriteLine(tempEntry.Value);
  30. }
  31. Console.ReadLine();
  32. }
  33. public static HybridDictionary GetSampleHybridDictionary()
  34. {
  35. // Declare HybridDictionary object
  36. HybridDictionary hybrid = new HybridDictionary();
  37. // Set value through Add method
  38. hybrid.Add("cat", 1);
  39. hybrid.Add("dog", 2);
  40. // Set value through indexer
  41. hybrid["rat"] = 0;
  42. // return HybridDictionary objects
  43. return hybrid;
  44. }
  45. }
  46. }


In the above code we can see there is a complete sample code of HybridDictionary to add and get elements. When we execute the above code get the following output.


Happy reading!
Abhishek


crazydeveloper Home Page 23 August 2015

Become a Fan