Jitesh Byahut 6/26/2014 2981

Generic Collections In C#

Introduction:

The System.Collections.Generic namespace contains classes that are used when you know the type of data to be stored in the collection and you want all elements in the collection to be of the same type.

Types of Generic Collections:


1. List

2. Stack

3. Queue

4. Dictionary

5. SortedList

List

List can store elements of any data type. Like Array, we don't need to specify the size of List at the time of it declaration. List collection class provide you to dynamically Add or Remove items from array. You can use List instead of array when you don't know the how many items will inserted. List is used when all items are same data type.

MethodDescriptions
Add(TValue)For add an item(at the end) in the List.
Insert(int index, TValue)For add an item at specific index in the List.
Remove(TValue)For remove an item from the List.
RemoveAt(int index)For remove an item at specific index from the List.
Reverse()For reverse the order of items in the List.
Sort()For sort the items in the List.
Clear()For eempty or removing all items from List.

        s// List Declaration

        List<string> list = new List<string>();       

 

        // Adding same data type elements in List

        list.Add("Asp.Net");

        list.Add("MVC");

        list.Add("C#");

        list.Add("Sql Server");

        list.Add("Jquery");      

 

        // Retreiving items from List     

        foreach (var item in list)

        {

            Response.Write(item);

            Response.Write("<br/>");

        }

        // Output

 

        // Asp.Net

        // MVC

        // C#

        // Sql Server

        // Jquery

       

        // Reverse the index of items in list

        list.Reverse();

 

        foreach (var item in list)

        {

            Response.Write(item);

            Response.Write("<br/>");

        }

        // Output

 

        // Jquery

        // Sql Server

        // C#

        // MVC

        // Asp.Net

 

        // You can Sort the list

        list.Sort();

 

        foreach (var item in list)

        {

            Response.Write(item);

            Response.Write("<br/>");

        }

        // Output

 

        // Asp.Net

        // C#

        // Jquery

        // MVC

        // Sql Server

 

        // Remove an item from list

        list.Remove("MVC"); // remove "MVC" item form the list

 

        // Remove a specific index item from list

        list.RemoveAt(0); // remove item which is at 0 index position i.e "Asp.Net"

 

        // Insert an item at specific index in arraylist

        list.Insert(0, "Asp-Helps"); // Insert an item at index 0 i.e. first position in the list

 

 

        // Remove all items from list

        list.Clear(); // Clear the list

Stack

Generic Stack collection is a kind of collection that can useful when you need to store same data type data in a specific order for sequential processing. A Stack works on principle of LIFO - Last In First Out, which means that last item inserted into the stack will be the first item to be removed from stack.

The adding of an item into stack is known as Push operation, removing an item from stack is known as Pop operation and if an item only read from top of stack is known as Peek operation.

MethodDescriptions
Push(TValue)For add an item in the Stack.
Pop()For remove an item from the Stack.
Peek()For retrieving an item without removing from the Stack.
Clear()For empty or removing all items from the Stack.

        // Stack Declaration

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

 

        // Add an item in stack

        stack.Push("Asphelps");

 

        // Count total number of items in stack

        int total = stack.Count;

 

        // Retrieving top item form stack without removing it.

        stack.Peek();

 

        // Remove item from stack

        stack.Pop();

 

        // Clear the stack

        stack.Clear();

 

        // Add items in stack      

 

        stack.Push("Asp.Net");

        stack.Push("MVC");

        stack.Push("C#");

        stack.Push("Sql Server");

        stack.Push("Jquery");

 

        // Retrieving items from stack as LIFO

        // Pop() method not only return the item, but also remove the item from the stack

        while (stack.Count != 0)

        {

            Response.Write(stack.Pop());

            Response.Write("<br/>");

        }

        // Output

 

        // Jquery

        // Sql Server

        // C#

        // MVC

        // Asp.Net

Queue

Generic Queue collection is a kind of collection that can useful when you need to store same datatype data in a specific order for sequential processing.

A Queue works on the principle of FIFO - First In First Out, which means that the first item inserted into Queue will be first remove form Queue.

The adding of an item into queue is known as Enqueue operation, removing an item from queue is known as Dequeue operation and if an item only read from top of queue is known as Peek operation.

MethodDescriptions
Enqueue(TValue)For add an item in the Queue.
Dequeue()For remove an item from the Queue.
Peek()For retrieving an item without removing from the Queue.
Clear()For empty or removing all items from the Queue.

        // Queue Declaration

        Queue<string> queue = new Queue<string>();

 

        // Add an item in queue

        queue.Enqueue("Asphelps");

 

        // Count total number of items in queue

        int total = queue.Count;  // Output:- 1

 

        // Retrieving top item form queue without removing it.

        queue.Peek();             // output:- Asphelps

 

        // Remove item from queue

        queue.Dequeue();         // removed item Asphelps from queue

 

        // Clear the queue

        queue.Clear();          // empty the queue

 

        // Adding different data type in queue

        queue.Enqueue("Asp.Net");

        queue.Enqueue("MVC");

        queue.Enqueue("C#");

        queue.Enqueue("Sql Server");

        queue.Enqueue("Jquery");

 

        // Retreiving items from queue as FIFO

        // Dequeue() method not only return the item, but also remove the item from the queue

        while (queue.Count != 0)

        {

            Response.Write(queue.Dequeue());

            Response.Write("<br/>");

        }

        // Output

 

        // Asp.Net

        // MVC

        // C#

        // Sql Server

        // Jquery

Dictionary

A Dictionary type enables you to store a set of elements and associate a key for each element. The key, instead of an index, is used to retrieve the element from the dictionary. This can be useful when you want to store data that comes from a table that has an Id column. You can create an object that holds the data and use the record’s Id as the key.

MethodDescriptions
Add(TKey, TValue)For add an item in the Dictionary.
Remove(TKey)For remove an item from the Dictionary.
Count()For count total items in the Dictionary.
Clear()For clear the Dictionary.

    class Student

    {

        public int Id { get; set; }

        public string Name { get; set; }

    }

 

        Dictionary<int, Student> dictionary = new Dictionary<int, Student>();

 

        dictionary.Add(1, new Student() { Id = 5, Name = "Amit" });

        dictionary.Add(2, new Student() { Id = 6, Name = "Deepak" });

        dictionary.Add(3, new Student() { Id = 7, Name = "Mishra" });

        dictionary.Add(4, new Student() { Id = 8, Name = "Anand" });

        dictionary.Add(5, new Student() { Id = 9, Name = "Ashutosh" });

 

        Response.Write(dictionary[5].Name);

 

        // Retrieving all keys from Dictionary

        foreach (var key in dictionary.Keys)

        {

            Response.Write(key);

            Response.Write("<br/>");

        }

        // Output

 

        // 1

        // 2

        // 3

        // 4

        // 5

 

        // Retrieving all items value from SortedList

        foreach (Student item in dictionary.Values)

        {

            Response.Write(item.Name);

            Response.Write("<br/>");

        }

        // Output

 

        // Amit

        // Deepak

        // Mishra

        // Anand

        // Ashutosh

 

        // Count total items in Dictionary

        dictionary.Count();

 

        // Remove an item which has key value 1

        dictionary.Remove(1);

 

        // Clear the Dictionary items

        dictionary.Clear();

SortedList

A SortedList is a collection that contains key-value pairs. The data is stored in SortedList basis of key and it can be accessed by the key or the index and because of it is sorted.

MethodDescriptions
Add(Tkey, TValue)For add an item in the SortedList.
ContainsKey(Tkey)For checking that key is exist or not in the SortedList.
ContainsValue(TValue)For checking that value is exist or not in the SortedList.
Count()For count total the items in the SortedList.
Remove(Tkey)For removing an item using item value from the SortedList.
RemoveAt(int index)For removing an item at specific index from the SortedList.
Clear()For eempty or removing all items from the SortedList.

        // SortedList Decration

        SortedList<string, string> sorted = new SortedList<string, string>();

 

        // Adding different data type in SortedList

        // Remember that key should be unique

        // Key data type should be same type

 

        sorted.Add("a", "Asp.Net");

        sorted.Add("b", "MVC");

        sorted.Add("c", "C#");

        sorted.Add("d", "Sql Server");

        sorted.Add("e", "Jquery");

 

        // Retrieving all keys from SortedList

        foreach (var key in sorted.Keys)

        {

            Response.Write(key);

            Response.Write("<br/>");

        }

        // Output

 

        // a

        // b

        // c

        // d

        // e     

 

        // Retrieving all items value from SortedList

        foreach (var item in sorted.Values)

        {

            Response.Write(item);

            Response.Write("<br/>");

        }

        // Output

 

        // Asp.Net

        // MVC

        // C#

        // Sql Server

        // Jquery

 

        // Count total number of items in SortedList

        int total = sorted.Count;

 

        // You can check out that particular key is exist or not in SortedList

        bool IsKeyExist = sorted.ContainsKey("d");

 

        // You can check out that particular Value is exist or not in SortedList

        bool IsValueExist = sorted.ContainsValue("C#");

 

        // Remove an item from SortedList by using key

        sorted.Remove("a"); // remove item which has key value 1  i.e. first item form the SortedList

 

        // Remove a specific index item from SortedList

        sorted.RemoveAt(1);  // remove item which is at index 1 position i.e. 2nd item

 

        // Clear the SortedList

        sorted.Clear();


Please give your feedback for improving this page