Skip to main content

Collections in C#


Collections in C#

In our previous article, we have learned about how we can use arrays in C#. Arrays in programming are used to group a set of related objects. So one could create an array or a set of Integers, which could be accessed via one variable name.

What is Collections in C#?

Collections are similar to Arrays, it provides a more flexible way of working with a group of objects.
In arrays, you would have noticed that you need to define the number of elements in an array beforehand. This had to be done when the array was declared.
But in a collection, you don't need to define the size of the collection beforehand. You can add elements or even remove elements from the collection at any point of time. This article will focus on how we can work with the different collections available in C#.

There are three distinct collection types in C#:
  • standard
  • generic
  • concurrent
The standard collections are found under the System.Collections. They do not store elements as specifically typed objects, but as objects of type Object. Standard collections include ArrayList, Hashtable, Queue, and Stack.

The generic collections are found under System.Collections.Generic. Generic collections are more flexible and are the preferred way to work with data. Generics enhance code reuse, type safety, and performance. The generic collections include Dictionary<T, T>, List<T>, Queue<T>, SortedList<T>, and Stack<T>.

Concurrent collections include BlockingCollection<T>, ConcurrentDictionary<T, T>, ConcurrentQueue<T>, and ConcurrentStack<T>.

Standard Collections

ArrayList in C#

ArrayList is a collection from a standard System.Collections namespace. It is a dynamic array. It provides random access to its elements. An ArrayList automatically expands as data is added. Unlike arrays, an ArrayList can hold data of multiple data types. Elements in the ArrayList are accessed via an integer index. Indexes are zero based. Indexing of elements and insertion and deletion at the end of the ArrayList takes constant time. Inserting or deleting an element in the middle of the dynamic array is more costly. It takes linear time.

Example

var arrayData = new ArrayList();

arrayData.Add("C#");
arrayData.Add("VB");
arrayData.Add(55);
arrayData.Add("Csharpnaija");
arrayData.Remove(55);

foreach (object el in arrayData)
{
     Console.WriteLine(el);
}

Generic Collections

List

List is a strongly typed list of objects that can be accessed by index. It can be found under System.Collections.Generic namespace.

Example

var proLangs = new List<string>();

proLangs.Add("C#");
proLangs.Add("Java");
proLangs.Add("NodJs");
proLangs.Add("NextJs");
proLangs.Add("Ruby");
proLangs.Add("Javascript");

Console.WriteLine(proLangs.Contains("C#"));

Console.WriteLine(proLangs[1]);
Console.WriteLine(proLangs[2]);

proLangs.Remove("C#");
proLangs.Remove("NextJs");

Console.WriteLine(proLangs.Contains("C#"));

proLangs.Insert(4, "PHP");

proLangs.Sort();

foreach (string lang in proLangs)
{
      Console.WriteLine(lang);
}


Collection initializers in C#

Collection initializers is a mechanism that allows us to specify elements to the collection during the object creation inside the {} brackets.

Example

var listElements = new List<int>() { 1, 2, 3, 4, 5, 6, 7 };

int sum = listElements.Sum();

Console.WriteLine(sum);

SortedList in C#

SortedList<T, T> represents a collection of key/value pairs that are sorted.

Example

var sortedList = new SortedList<string, int>();

sortedList.Add("Csharpnaija Admin", 1);
sortedList.Add("Authors", 3);
sortedList.Add("Users", 10);

if (sortedList.ContainsKey("Authors"))
{
     Console.WriteLine("There are Authors in the list");
}

foreach (var pair in sortedList)
{
    Console.WriteLine(pair);
}

LinkedList in C#

LinkedList is a generic doubly linked list in C#. LinkedList only allows sequential access. LinkedList allows for constant-time insertions or removals, but only sequential access of elements. Because linked lists need extra storage for references, they are impractical for lists of small data items such as characters. Unlike dynamic arrays, arbitrary number of items can be added to the linked list (limited by the memory of course) without the need to reallocate, which is an expensive operation.

Example
    var linkListnums = new LinkedList<int>();

            linkListnums.AddLast(23);
            linkListnums.AddLast(34);
            linkListnums.AddLast(33);
            linkListnums.AddLast(11);
            linkListnums.AddLast(6);
            linkListnums.AddFirst(9);
            linkListnums.AddFirst(7);

            LinkedListNode<int> node = linkListnums.Find(6);
            linkListnums.AddBefore(node, 5);

            foreach (int num in linkListnums)
            {
                Console.WriteLine(num);
            }

Dictionary in C#

A dictionary, also called an associative array, is a collection of unique keys and a collection of values, where each key is associated with one value. Retrieving and adding values is very fast. Dictionaries take more memory because for each value there is also a key.
  
Example

 var states = new Dictionary<string, string>();

            states.Add("NS", "Nasarawa");
            states.Add("KN", "Kano");
            states.Add("KD", "Kaduna");
            states.Add("KT", "Katsina");
            states.Add("FCT", "Abuja");
            states.Add("NG", "Niger");

            Console.WriteLine(states["NS"]);
            Console.WriteLine(states["KN"]);

            Console.WriteLine("Dictionary has {0} items",
                states.Count);

            Console.WriteLine("Keys of the dictionary:");

            var keys = new List<string>(states.Keys);

            foreach (string key in keys)
            {
                Console.WriteLine("{0}", key);
            }

            Console.WriteLine("Values of the dictionary:");

            var vals = new List<string>(states.Values);

            foreach (string val in vals)
            {
                Console.WriteLine("{0}", val);
            }

            Console.WriteLine("Keys and values of the dictionary:");

            foreach (KeyValuePair<string, string> kvp in states)
            {
                Console.WriteLine("Key = {0}, Value = {1}",
                    kvp.Key, kvp.Value);
            }

Queues in C#

A queue is a First-In-First-Out (FIFO) data structure. The first element added to the queue will be the first one to be removed. Queues may be used to process messages as they appear or serve customers as they come. The first customer which comes should be served first.

Example

  var msgs = new Queue<string>();
             msgs.Enqueue("Message 1");
            msgs.Enqueue("Message 2");
            msgs.Enqueue("Message 3");
            msgs.Enqueue("Message 4");
            msgs.Enqueue("Message 5");

            Console.WriteLine(msgs.Dequeue());
            Console.WriteLine(msgs.Peek());
            Console.WriteLine(msgs.Peek());

            Console.WriteLine();

            foreach (string msg in msgs)
            {
                Console.WriteLine(msg);
            }

Stacks in C#

A stack is a Last-In-First-Out (LIFO) data structure. The last element added to the queue will be the first one to be removed. The C# language uses a stack to store local data in a function. The stack is also used when implementing calculators.

Example

  var myStack = new Stack<int>();
             myStack.Push(1);
            myStack.Push(4);
            myStack.Push(3);
            myStack.Push(6);
            myStack.Push(4);

            Console.WriteLine(myStack.Pop());
            Console.WriteLine(myStack.Peek());
            Console.WriteLine(myStack.Peek());

            Console.WriteLine();

            foreach (int item in myStack)
            {
                Console.WriteLine(item);
            }
Thank you, please subscribe and share if you find it useful. Read more about collection from here

Comments

Popular posts from this blog

Interface with real life Examples

Interfaces with real life examples An interface is a programming structure/syntax that allows the computer to enforce certain properties on an object (class). For example, say we have a car class and a tricyclic class and a truck class. Each of these three classes should have a start engine() action. How the "engine is started" for each vehicle is left to each particular class, but the fact that  they must  have a start engine action is the domain of the interface. The syntax of an Interface We can implement single interface or multiple interfaces to the class. By default interfaces are public. We declare interface by using "interface" keyword. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CsharpnaijaInterfaceTutorial {     interface IEngine     {         void Start();     }...

The Out Parameter with Example in C#

  The Out Parameter with Example in C# In C#,  out  keyword is used to pass arguments to the method as a  reference type . The  out  keyword same as the  ref  keyword but the only difference is  out  doesn’t require a variable to be initialized before we pass it as an argument to the method but the  variable  must be initialized in called method before it returns a value to the calling method. The out parameter in C# is also useful to return more than one value from methods. Declaration of C# Out Parameter Following is a simple example of using  out  parameters in C#.   int x; // No need to initialize variable OutParameterMultTest ( out x ) ;   From the above declaration, we just declared a variable  x  and pass it to the method by using  out  parameter without assigning any value but as discussed, the variable must be initialized in called method before it returns a value...