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
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(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
Post a Comment