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

Classes in C# Explained

C# Class Explained A class is nothing but an encapsulation of properties and methods that are used to represent a real-time entity, as explained by Guru99 . For instance, if you want to work with Guest’s data as in our previous DataDriven Web application . The properties of the Guest would be the Id, GuestName, Address, Phone number etc of the Guest. The methods would include the entry and modification of Guest data. All of these operations can be represented as a class in C# as shown below. using System; namespace CsharpnaijaClassTutorial {     public class Guest     {         public int Id { get ; set ; }         public string GuestName { get ; set ; }         public string Address { get ; set ; }         public string WhomToSee { get ; set ; }     ...

ASP.NET MVC Views

Views in ASP.NET MVC Application explained Find a related article By  Steve Smith  and  Luke Latham from Microsoft Corporation here In the Model-View-Controller (MVC) pattern, the  view  handles the application's data presentation and user interaction. A view is an HTML template with embedded  Razor markup . Razor markup is code that interacts with HTML markup to produce a webpage that's sent to the client. In ASP.NET MVC, views are  .cshtml  files that use the  C# programming language  in Razor markup. Usually, view files are grouped into folders named for each of the application's  controllers . The folders are stored in a  Views  folder at the root of the application as shown: The  Home  controller is represented by a  Home  folder inside the  Views  folder.  The  Home  folder contains the views for the  About ,  Contact , and  Index...

ASP.NET MVC Routing

ASP.NET MVC Routing ASP.NET MVC routing is a pattern matching system that is responsible for mapping incoming browser requests to specified MVC controller actions. When the ASP.NET MVC application launches then the application registers one or more patterns with the framework's route table to tell the routing engine what to do with any requests that matches those patterns. When the routing engine receives a request at runtime, it matches that request's URL against the URL patterns registered with it and gives the response according to a pattern match. Routing pattern is as follows A URL is requested from a browser, the URL is parsed (that is, break into controller and action), the parsed URL is compared to registered route pattern in the framework’s route table, if a route is found, its process and send response to the browser with the required response, otherwise, the HTTP 404 error is send to the browser. Route Properties ASP.NET MVC routes are res...