C#.Net Collection tutorial

collection in C#.Net
SharePoint deveopment training course

This C#.Net tutorial explains, what is a collection in C#.Net? What are various collection types in c#.net? What are hash table in c#.net?

What is a collection in C#.Net?

We know the array is used to store a set of the homogeneous data type objects. But the collection will store the related object that does not means all the elements having the same data type as an array.

The array has some following limitation such as the array size is fixed we cannot add and remove the item in an array. We can not insert an item into the middle of the array and we can not remove the item from the middle of the array.

The collection is the same as an array but it is overcoming the above limitation. The collection allows a more flexible way to work with a set of objects. We can also be called the collection as a dynamic array.

Before using Collection we need to add “System. Collections” namespace.

How Array size can not increased in Array in C#.Net?

We know previously that array are fixed length that means once the array is declared in a program the size can not be changed.

For example, int[] marks=new int[20]; the statement means the array can only contain 20 value we can not increase the 20 value to 50. So for that, we need to create a new array and copy the old array element then only possible.

Collections contains some classes, array list one of them. Now I have take one example of array list.

Before work with collection first, we need to import a namespace “using System. Collections”. The ArrayList collection is class so to use the class first we need to create an instance of a class in the declaration.

Note:If our collection contains same data type then we can use the System.Collections.Generic namespace.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList arlst = new ArrayList();
        }
    }
}

Now we will see what is the auto resizeable property of collection:

The Collection class provides one Capacity property that will say how many numbers of the item that can be stored in a collection. When we run the “Console.WriteLine(arlst.Capacity);” we will get 0 as output. When we add the item using “arlst.Add(100)” still it is not showing an error. Because when we add a new item in the ArrayList then it will automatically resize. Which is called the Auto resizeable property of an array.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList arlst = new ArrayList();
            Console.WriteLine("Before adding item to ArrayList the size is "+ arlst.Capacity);
            arlst.Add(100);
            Console.WriteLine("After adding one item the ArrayList size is "+arlst.Capacity);
        }
    }
}
c# net arraylist collection
c# net arraylist collection

Note: We can also add the items to ArrayList without using the Add() method. Instance creation time only we can add the item within “{” bracket. Put “,” between each item.

static void Main(string[] args
{
 ArrayList arlst = new ArrayList() { 100, 200, 300, 400, 500 };
 foreach (int items in arlst)
 Console.WriteLine(items);
 }

In the above output, we can see previously the capacity is 0 but after adding it going to be 4. That means it’s allocating the memory space of 4 items at a time. When we add one item in the Array list collection class its directly allocating the memory for 4 items. In the below code I have added more 3 items then I have checked the capacity it is showing 4 only. But when we will add the 5 number items it will allocate 8 items memory space suddenly.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList arlst = new ArrayList();
            Console.WriteLine("Before adding item to ArrayList the size is "+ arlst.Capacity);
            arlst.Add(100);
            Console.WriteLine("After adding one item the ArrayList size is "+arlst.Capacity);
            arlst.Add(90);arlst.Add(60);arlst.Add(70);
            Console.WriteLine("After adding more three item the capacity is " + arlst.Capacity);
        }
    }
}
collections in c# .net with examples
collections in c# .net with examples

When I have added one more value the memory space will increase to 8. Always the size will be double when we add the 9th items the memory space will allocate to 16.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList arlst = new ArrayList();
            Console.WriteLine("Before adding item to ArrayList the size is "+ arlst.Capacity);
            arlst.Add(100);
            Console.WriteLine("After adding one item the ArrayList size is "+arlst.Capacity);
            arlst.Add(90);arlst.Add(60);arlst.Add(70);arlst.Add(39);
            Console.WriteLine("Now the capacity is " + arlst.Capacity);
        }
    }
}
c#.net collections with examples
c#.net collections with examples

Using the foreach loop how to display all the itms of array list.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList arlst = new ArrayList();
            Console.WriteLine("Before adding item to ArrayList the size is "+ arlst.Capacity);
            arlst.Add(100);
            Console.WriteLine("After adding one item the ArrayList size is "+arlst.Capacity);
            arlst.Add(90);arlst.Add(60);arlst.Add(70);arlst.Add(39);arlst.Add(60); arlst.Add(70); arlst.Add(39); arlst.Add(70); arlst.Add(39);
            Console.WriteLine("Now the capacity is " + arlst.Capacity);
           foreach(int items in arlst)
                Console.WriteLine(items);
        }
    }
}
collections in c#
collections in c#

How to insert item in the middle of ArrayList in C#.Net?

The ArrayList collection class provides the Insert method to add item in the middle of the array list. the Insert method contains two parameters one is in which position we need to add the item and the second one is what we want to insert. In the below example I have added 50 in the 1st position.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList arlst = new ArrayList();
            Console.WriteLine("Before adding item to ArrayList the size is " + arlst.Capacity);
            arlst.Add(100);
            Console.WriteLine("After adding one item the ArrayList size is " + arlst.Capacity);
            arlst.Add(90); arlst.Add(60); arlst.Add(70); arlst.Add(39); arlst.Add(60); arlst.Add(70); arlst.Add(39); arlst.Add(70); arlst.Add(39);
            Console.WriteLine("Now the capacity is " + arlst.Capacity);
            Console.WriteLine("Before inserting the item");
            foreach (int items in arlst)
                Console.WriteLine(items);
            arlst.Insert(1,50);
            Console.WriteLine("After inserting the items");

            foreach (int items in arlst)

                Console.WriteLine( items);
        }
    }
}
c# collection foreach
c# collection foreach

How to remove items form the Array list in C#.Net?

Array list collection class provide remove method to remove item from the list. We just need to write the ArrayList class instance.Remove(), with in the bracket we need to pass which value we want to delete. We can also delete from the particular index of array list by using RemoveAt method we just need to pass the index number.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList arlst = new ArrayList();
            Console.WriteLine("Before adding item to ArrayList the size is " + arlst.Capacity);
            arlst.Add(100);
            Console.WriteLine("After adding one item the ArrayList size is " + arlst.Capacity);
            arlst.Add(90); arlst.Add(60); arlst.Add(70); arlst.Add(39); arlst.Add(60); arlst.Add(70); arlst.Add(39); arlst.Add(70); arlst.Add(39);
            Console.WriteLine("Now the capacity is " + arlst.Capacity);
            Console.WriteLine("Before inserting the item");
            foreach (int items in arlst)
                Console.WriteLine(items);
            arlst.Insert(1,50);
            Console.WriteLine("After inserting the items");
            arlst.Remove(90);
            arlst.RemoveAt(3);
           
            foreach (int items in arlst)

                Console.WriteLine( items);
        }
    }
}
remove item from collection c#
remove item from collection c#

C#.Net Collection Types

The C#.Net provide 3 type of collection

  1. Standard
  2. Generic
  3. Concurrent

Standard: The Standard collection comes under the system.Collection namespace. It also called Nongeneric collection. It can hold the object of a different type. In all the above example I have taken the standard collection. The class comes under System. Collections namespace is

ArrayList, Hashtable, Queue, Stack

Generic: The generic collection comes under System.Collection.Generic namespace. We can create a generic collection using the classes which the System.Collection.Generic namespace contains. The generic collection is preferred if the collection has the same data type. The class under the generic namespace are as following

List, Stack,LinkedList, Dictionary

Concurrent: The concurrent collection classes come under the System.Collections.Concurrent namespace. The above namespace provides some of the threads safe classes such as

BlockingCollection, ConcurrentBag, ConcurrentStack, ConcurrentQueue.

HashTable in C#.Net

The HashTable is a collection type in which we need to store 2 value one is key and another one is value. These key and value combine make a single element for the hash table. In the below example the hashtable collection contains 3 elements, each element is a pair of key and value. The “OS” is the Key and “Operating System” is the value.

(“OS”, “Opearating System”);
(“OOPS”, “Object Oriented Programing Language”);
(“SS”, “Signal System”);

In the below code within the main function first I have declared a hashtable collection using Hashtable data type, “htbl” is one variable. Using the new keyword create an instance and assign to the variable. Example: “Hashtable htbl = new Hashtable();”. To add the value to the collection htbl.Add() method is used. In the Add method, we need to pass two parameters one is key and another one is value.

Now we will see what is Icollection?

In the hashtable we can not directly show the hashtable element first we need to retrieve the values. So Icollection interface came in the picture. This Icollection interface act as a data type using that we can declare a variable as “keyvalue” and store hashtable key value.

Then I have used a for each loop to display the element of hashtable collection class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;

namespace collectioncsharp
{
    class Program
    {
        static void Main(string[] args)
        {
            
                {
                    Hashtable htbl = new Hashtable();
                    htbl.Add("OS", "Opearating System");
                    htbl.Add("OOPS", "Object Oriented Programing Language");
                    htbl.Add("SS", "Signal System");
                    htbl.Add("DCCN", "Data Communication Networking");

                    ICollection keyvalue = htbl.Keys;//create a hashtable collection

                    foreach (String sub in keyvalue)
                    {
                        Console.WriteLine(htbl[sub]);
                    }
                    Console.ReadKey();
                }           
        }
    }
}

The output screen will look like below

c# hashtable get value by key
c# hashtable get value by key

ContainsKey, ContainsValue and Remove() method of HashTable in C#.net

The ContainsKey method will check in the Hashtable that specified key is present or not. Like the ConatinsValue() will check the specified value is present or not in the hashtable. The output will come in true or false value.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;

namespace CollectionHashTable
{
    class Program
    {
        static void Main(string[] args)
        {
            Hashtable htbl = new Hashtable();
            htbl.Add("OS", "Opearating System");
            htbl.Add("OOPS", "Object Oriented Programing Language");
            htbl.Add("SS", "Signal System");
            htbl.Add("DCCN", "Data Communication Networking");
            Console.WriteLine(htbl.ContainsKey("SS"));
            Console.WriteLine(htbl.ContainsValue("Signal"));
        }
    }
}
collection-hashtable-containskey-c#
collection-hashtable-containskey-c#

Remove(): The remove method is used to remove the specified key from the hashtable.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;

namespace CollectionHashTable
{
    class Program
    {
        static void Main(string[] args)
        {
            Hashtable htbl = new Hashtable();
            htbl.Add("OS", "Opearating System");
            htbl.Add("OOPS", "Object Oriented Programing Language");
            htbl.Add("SS", "Signal System");
            htbl.Add("DCCN", "Data Communication Networking");
            htbl.Remove("DCCN");
            Console.WriteLine(htbl.ContainsKey("SS"));
            Console.WriteLine(htbl.ContainsValue("Signal"));
            ICollection key = htbl.Keys;
            foreach(string sub in key)
            {
                Console.WriteLine(htbl[sub]);
            }
            
       }
   }
}
hashtable in c# with example
hashtable in c# with example

You may like following C#.Net tutorials:

In the above C#.Net blog, we were discussed what is a collection, a different type of collection in C#.Net. Examples of Array list class collection and HashTable in C#.Net.

Check out Best Alternative to InfoPath -> Try Now

free sharepoint training

SharePoint Online FREE Training

JOIN a FREE SharePoint Video Course (3 Part Video Series)

envelope
envelope

About Bijay Kumar

I am Bijay from Odisha, India. Currently working in my own venture TSInfo Technologies in Bangalore, India. I am Microsoft Office Servers and Services (SharePoint) MVP (5 times). I works in SharePoint 2016/2013/2010, SharePoint Online Office 365 etc. Check out My MVP Profile.. I also run popular SharePoint web site SharePointSky.com

View all posts by Bijay Kumar →