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#

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#

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#

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

The String.Join Method in C# Explained

The String.Join Method in C#   The string.Join concatenates the elements of a specified array or the members of a collection, using the specified separator between each element or member. Overloads of string.Join Method Description Join(Char, Object[]) Concatenates the string representations of an array of objects, using the specified separator between each member. Join(Char, String[]) Concatenates an array of strings, using the specified separator between each member. Join(String, IEnumerable<String>) Concatenates the members of a constructed IEnumerable<T> collection of type String, using the specified separator between each member. Join(String, Object[]) Concatenates the elements of an object array, using the specified separator between each element. Join(String, String[]) Concatenates all the elements of a string array, usi...

Most Popular Programming Languages in 2020

Most Popular Programming Languages in 2020 In this blog post, you will learn about the most popular programming languages in 2020 for creating the best web applications. Check its pros and cons. Analyzed by technostacks Not very long ago, just a few people were considered to be computer programmers, and the general public viewed them with awe. In this digital age that we are now living in, however, a large number of IT jobs need a solid grasp of one or more programming languages. Whether one wants to develop a mobile app or get a certification for having programming knowledge, or even to learn new skills, one needs to opt for the right programming language. Below mentioned eight most popular programming languages which are in demand for software development and web applications. This is the most used programming languages in 2019 and will be in 2020. For each, there is little information about the language, benefits and its complexity, as well as about its usage. One must...

HashTable in C# with Example

  HashTable in C# with Example Hashtable  is used to store a collection of key/value pairs of different  data types  and are organized based on the hash code of the key.   Generally, the hashtable object will contain buckets to store elements of the collection. The bucket here, is a virtual subgroup of elements within the hashtable and each bucket is associated with a hash code, which is generated based on the key of an element.   In C#, hashtable is same as a  dictionary  object but the only difference is that the  dictionary  object is used to store a key-value pair of same  data type  elements.   When compared with  dictionary  object, the hashtable will provide a lower performance because the hashtable elements are of object type so the boxing and unboxing process will occur when we are storing or retrieving values from the hashtable.   C# HashTable Declaration Hashtable is a non-generic type...