articles

Home / DeveloperSection / Articles / Collections in C#

Collections in C#

priyanka kushwaha5344 10-Mar-2015

In this article, I’m explaining about collections in C#

What is collection?

Collection classes are specialized classes for data storage and retrieval. These classes provide support for stacks, queues, lists and hash tables.

Types of collections:

1.       System.Collections.Generic Classes

2.       System.Collections.Concurrent Classes

3.       System.Collections Classes 


System.Collections collection:

The classes in System.collection namespace allows storing elements of any data type in a single collection. Every element is stored as an object of type object. So these collection classes are typically referred as non-generic classes. The following tabular lists some of the frequently used classes in System.Collections namespace. 

ArrayList: Represents an array of objects whose size is dynamically increased as required.

Example of Arraylist:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Collections;

namespace ArraylistDemo

{

    classProgram

    {

        staticvoid Main(string[] args)

        {

            int[] arr = newint[4] { 1, 2, 3, 4 };

            string[] str = { "Pawan", "Priyanka", "Kamlakar" };

            string name = "Pawan";

//New ArrayList

            ArrayList arrlist = newArrayList();

            arrlist.Add(str);

            arrlist.Add(arr);

            arrlist.Add(name);

            foreach (object obj in arrlist)

            {

                Type objtype = obj.GetType();

                if (objtype.IsArray)

                {

                    if (objtype == typeof(System.Int32[]))

                    {

                        int[] strlist = (int[])obj;

                        for (int i = 0; i < strlist.Length; i++)

                            Console.WriteLine(strlist[i]);

                    }

                    else

                    {

                        String[] stringArray = (String[])obj;

                        for (int i = 0; i < stringArray.Length; i++)

                            Console.WriteLine(stringArray[i]);

                    }

                }

                 else

                {

                    Console.Write(obj.ToString());

                }

            }

            Console.ReadKey();

        }

    }

}

 

 Output:

Pawan

Priyanka

Kamlakar

1

2

3

4

Pawan

               

Hashtable: Represents a collect of key & value pair that are organized based on the hash code of the key.

Example of HastTable:

using System; 

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Collections;

namespace HashDemo

{

    class Program

    {

        static Hashtable getHashData()

        {

            Hashtable hsttbl = new Hashtable();

            string str;

            for(int i=0;i<3;i++)

            {

                str=Console.ReadLine();

                hsttbl.Add(i, str);

            }

            return hsttbl;

        }

        static void Main(string[] args)

        {

            Hashtable hasttable = getHashData();

            foreach (DictionaryEntry entry in hasttable)

            {

                Console.WriteLine("{0}{1}",entry.Key,entry.Value);

            }

            Console.ReadKey();

        }

    }

}

Output:

1 priyanka

2 Sita

3 Ram 

Queue: Represents a first in first out collection of objects. 

Stack: Represents a last in first out collection of object. 

System.Collections.Generic classes                 

A generic collection is typically used to store the items in of the same data type. It enforces strong typing by allowing only the desired data type to be added. Datatype has to be specified at the time of instantiation of generic classes.

The following tabular lists some of the frequently used classes of this namespace:

Dictionary<TKey,TValue>: Represents a collection of key & value pairs that are organized based on the key.

Example:

ing System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
namespace DictionaryExample 
{ 
 class Program 
 { 
 static void Main(string[] args) 
 { 
 Dictionary<string, string>DictValues = new Dictionary<string, string>(); 
 DictValues.Add("cat","feline"); 
 DictValues.Add("dog", "Canine"); 
 string test; 
 Console.Write("Enter the key"); 
 test=Console.ReadLine(); 
 if (DictValues.ContainsKey(test)) 
 { 
 string value=DictValues[test]; 
 Console.Write("Value:"+value); 
 } 
 Console.ReadKey(); 
 } 
 } 
}

 

Output:

Enter key: dog

Value: Cania

List<T>: Represents a list of objects that can be accessed by index. Provides methods to search, sort and modified lists.

Example:

 

using System;

using System.Collections;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace IListExample

{

    classProgram

    {

        staticvoid Main(string[] args)

        {

            IList<string>ilst = newList<string>();

            ilst.Add("Sita");

            ilst.Add("Geeta");

            foreach (string num in ilst)

                Console.WriteLine(num);

            Console.ReadKey();

        }

    }

}

Output:

Sita

Geeta

 

Queue<T>: Represent a first in first out (FIFO) collection of objects.

Example:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Collections;

namespace QueueListDemo

{

    classProgram

    {

        staticvoid Main(string[] args)

        {

            ArrayList list = newArrayList();

            String[] str=newString[5];

           

            for (int i = 0; i< str.Length; i++)

            {

           Console.WriteLine("enter  string");

            str[i]=Console.ReadLine();

            }

//New Queue

            Queue<string>que = newQueue<string>(str);

            Console.WriteLine("queue representation");

            foreach (var item in que)

              Console.WriteLine(item);

        

 

            Console.WriteLine("Enqueue Example");

            string stren;

            Console.WriteLine("Enter a string");

          stren= Console.ReadLine();

//Add an item in Queue

            que.Enqueue(stren);

            Console.WriteLine("Enqueue Representation");

            foreach (var en in que)

                Console.WriteLine(en);

//Remove the oldest item from Queue

            que.Dequeue();//Remove first element;

            Console.WriteLine("After removal the element in the  queue are:");

            foreach (var en in que)

                Console.WriteLine(en);

            Console.ReadKey();

        }

    }

}

Output:

1

2

3

4

5

 

SortedList<T>: Represents a collection of key &value pairs that are sorted by key based on the associated IComparer<T> implement.

Example:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Collections;

namespace SortListExample

{

    classProgram

    {

        staticvoid Main(string[] args)

        {

            SortedList s1 = newSortedList();

            s1.Add("1","B");

            s1.Add("2", "T");

            s1.Add("3", "W");

            foreach (string st in s1.Values)

                Console.WriteLine(st);

            Console.ReadKey();

        }

    }

}

 

Stack<T>: Represent a last in first out collection of objects.

Example of Stack:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Collections;

namespace QueueListDemo

{

    classProgram

    {

        staticvoid Main(string[] args)

        {

            ArrayList list = newArrayList();

            String[] str = newString[5];

 

            for (int i = 0; i < str.Length; i++)

            {

                Console.WriteLine("enter  string");

                str[i] = Console.ReadLine();

            }

 

            Stack<string>stk = newStack<string>(str);

            Console.WriteLine("Stack representation");

            foreach (var item in stk)

                Console.WriteLine(item);

 

            Console.ReadKey();

        }

    }

}

Output:

5

4

3

2

1

 System.Collections.Concurrent Classes

The System.Collections.Concurrent namespace provide efficient thread-safe operations for accessing collection items concurrently from multiple threads.

Some classes included in the System.Collections.Concurrent namespace are

BlockingCollection<T>: Provides blocking and bounding capabilities for thread-safe collections that implement IProducerConsumerCollection<T>.

Example:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Collections;

using System.Collections.Concurrent;

using System.Threading;

 

namespace BlockingCollectionExample

{

 

    classProgram

    {

        privatestaticBlockingCollection<string> que = newBlockingCollection<string>();

        privatestaticvoid RunProducer()

        {

            int itemCount = 100;

            while (itemCount-- > 0)

            {

                que.Add(itemCount + "-" + Guid.NewGuid().ToString()+"Producer");

                Thread.Sleep(500);

            }

        }

        privatestaticvoid RunConsumer()

        {

            foreach (var item in que.GetConsumingEnumerable())

                Console.WriteLine(DateTime.Now.ToString("HH:mm:ss.ffff")+"|"+item);

        }

        publicstaticvoid start()

        {

            var producerWorker = Task.Factory.StartNew(()=>RunProducer());

            var ConsumerWorker = Task.Factory.StartNew(() => RunConsumer());

        }

        staticvoid Main(string[] args)

        {

            start();

            Console.ReadKey();

         

        }

    }

}

 

Output:

Collections in C#

 

ConcurrentBag<T>: Represent a thread-safe, unordered collection of objects.

Example:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Collections.Concurrent;

using System.Threading;

using System.Collections;

namespace ConcurrentBagExample

{

    classProgram

    {

 

         staticConcurrentBag<int> conbag = newConcurrentBag<int>();

       

     

        staticvoid Main(string[] args)

        {

        

            conbag.Add(1);

            conbag.Add(2);

            conbag.Add(3);

            int result;

            if (conbag.TryPeek(out result))

            { Console.WriteLine("TryPeek:{0}", result);

            }

            if (conbag.TryTake(out result))

                Console.WriteLine("TryTake:{0}", result);

            if (conbag.TryPeek(out result))

                Console.WriteLine("TryPeek:{0}", result);

            Console.ReadKey();

        }

    }

}

 

Output:

TryPeek: 3

TryTake: 3

TryPeek: 2

ConcurrentDictionary<TKey,TValue>: Represents thread-safe collection of key/value pairs that can be accessed by multiple threads concurrently.

Example:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Collections.Concurrent;

namespace ConcurrentDictionaryExample

{

    classProgram

    {

        staticvoid Main(string[] args)

        {

            var con = newConcurrentDictionary<string, int>();

            con.TryAdd("String1",1);

            con.TryAdd("String2",2);

            Console.WriteLine(con["String1"]);

            //Try to update if value is 3(this fails)

            con.TryUpdate("String1", 10, 3);

            Console.WriteLine(con["String1"]);

          //Try to update if value is 1(this works)

           con.TryUpdate("String1",10,1);

           Console.WriteLine(con["String1"]);

            Console.ReadKey();

        }

    }

}

 

Output:

1

1

10

ConcurrentQueue<T>: Represent a thread-safe first in first out collection

Example:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Collections.Concurrent;

using System.Threading;

namespace ConcurrentQueue

{

    classProgram

    {

        staticlong _total;

        staticConcurrentQueue<int> _queued;

     

   

        staticvoid ProcessQueue()

        {

            int value;

 

            while (_queued.TryDequeue(out value))

            {

                Interlocked.Add(ref _total, value);

            }

        }

        staticvoid Main(string[] args)

        {

            IEnumerable<int> numbers = Enumerable.Range(1, 1000000);

            _queued = newConcurrentQueue<int>(numbers);

            _total = 0;

 

            Task task1 = Task.Run(() => ProcessQueue());

            Task task2 = Task.Run(() => ProcessQueue());

 

            Task.WaitAll(task1, task2);

 

            Console.WriteLine("Total: {0}", _total);

            Console.ReadKey();

        }

    }

}

Output:

Total: 500000500000

ConcurrentStack<T>: Represent a thread-safe last in first out collection.

Example:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Collections;

using System.Threading;

using System.Collections.Concurrent;

 

namespace ConcurrentStackExample

{

    classProgram

    {

     staticConcurrentStack<string> constack = newConcurrentStack<string>();

      static  void pushMethod()

        {

            string str;

            for (int i = 0; i < 5; i++)

            {

              

                Console.WriteLine("Enter the element");

                str = Console.ReadLine();

                constack.Push(str);

            }

        }

        staticvoid Main(string[] args)

        {

            pushMethod();

            int counter = 0;

            Task[] stkTask = newTask[10];

 

            Console.WriteLine("Stack Representation");

            for (int i = 0; i < stkTask.Length; i++)

            {

                stkTask[i] = Task.Factory.StartNew(() =>

                {

                    while (constack.Count > 0)

                    {

                        string currelement;

                        bool success = constack.TryPop(out currelement);

                        if (success)

                        {

                            Interlocked.Increment(ref counter);

                        }

                        Console.WriteLine(currelement);

                    }

                }

               );

            }

            Task.WaitAll(stkTask);

            Console.WriteLine("Counter: {0}", counter);

          

            Console.ReadKey();

        }

    }

}

 

Output:

Enter the element

4

Enter the element

3

Enter the element

2

Enter the element

1

Enter the element

5

Stack Representation

5

1

2

3

4

Counter: 5

 

 

 


Updated 07-Sep-2019

Leave Comment

Comments

Liked By