Collection C#
Collection C#
In C#, collection represents group of objects. By the help of collections, we can perform
various operations on objects such as
store object
update object
delete object
retrieve object
search object, and
sort object
We can store objects in array or collection. Collection has advantage over array. Array has
size limit but objects stored in collection can grow or shrink dynamically.
Types of Collections in C#
There are 3 ways to work with collections. The three namespaces are given below:
System.Collections.Generic classes
System.Collections classes (Now deprecated)
System.Collections.Concurrent classes
System.Collections.Generic Classes
class Program
{
public static void Main()
{
// create a list named number that contains integer data items
List<int> number = new List<int>();
number.Add(1);
number.Add(2);
number.Add("Programiz");
Console.WriteLine(number[1]); //
}
}
Here, we have defined the type of the number list, which is int.
Some System.Collections.Generic Classes
In C#, following are the classes that come under System.Collections.Generic namespace:
1. List Class
The List<T> class is used to store multiple elements of the same data type that can be
accessed using the indexes. We can add, insert and remove elements inside the list. Moreover,
we can dynamically change the size of the list.
2. Stack Class
The Stack<T> class is also generic, which means we store data elements of the same data
type.
In stack, the elements are stored in LIFO(Last In First Out) manner. With the help of methods,
we can perform operations in stack:
3. Queue Class
In Queue<T> class, the objects are stored in FIFO(First In First Out) manner. Here, the
elements are inserted at one end and removed from the other. It is implemented using a
circular queue. We can perform operations using methods like:
Enqueue()- add elements
Dequeue() - remove elements
4. Dictionary<TKey, TValue>
Dictionary Characteristics
4. SortedList Class
The SortedList<TKey,TValue> is an array that consists of key/value pairs that are sorted in
an order. Every key inside SortedList<TKey,TValue> must be unique, and using those keys
we can access the elements inside it. null value is not accepted as a key.
System.Collections Classes
In C#, the System.Collections classes help us to create a non-generic collection.
For this we use System.Collections namespace. Using this we can create classes where we
can add data elements of multiple data types.
Following are some of the classes that are in System.Collections namespace:
1. ArrayList Class
ArrayList is non-generic which means we can store elements of multiple data types. We use
the ArrayList class to implement the functionality of resizable arrays. Duplicate elements are
allowed inside ArrayList.
We can use the sort method to sort the elements inside it.
2. Hashtable Class
Hashtable is also non-generic which consists of key/value pairs that are managed using the
hash code of the particular key. The key cannot be null however a value can be null. We can
perform dynamic allocation of the memory inside Hashtable.
3.SortedList
SortedList stores key and value pairs. It automatically arranges elements in ascending order of key by
default. C# includes both, generic and non-generic SortedList collection.
4. Queue
Queue stores the values in FIFO style (First In First Out). It keeps the order in which the values were
added. It provides an Enqueue() method to add values and a Dequeue() method to retrieve values from
the collection. C# includes generic and non-generic Queue.
System.Collections.Concurrent Classes
There can be situations when multiple threads are trying to execute the same piece of code.
The code is said to be "thread-safe" if it can be executed correctly irrespective of multiple
threads accessing concurrently.
It is recommended to use System.Collections.Concurrent classes rather
than System.Collections and System.Collections.Generic classes when multiple threads are
accessing the collection.
Some of the thread-safe collection classes are:
ConcurrentStack<T>
ConcurrentQueue<T>
ConcurrentDictionary<TKey,TValue>
C# List<T>
C# List<T> class is used to store and fetch elements. It can have duplicate elements. It is
found in System.Collections.Generic namespace.
C# List<T> example
Let's see an example of generic List<T> class that stores elements using Add() method and
iterates the list using for-each loop.
1. using System;
2. using System.Collections.Generic;
3.
4. public class ListExample
5. {
6. public static void Main(string[] args)
7. {
8. // Create a list of strings
9. var names = new List<string>();
10. names.Add("Sonoo Jaiswal");
11. names.Add("Ankit");
12. names.Add("Peter");
13. names.Add("Irfan");
14.
15. // Iterate list element using foreach loop
16. foreach (var name in names)
17. {
18. Console.WriteLine(name);
19. }
20. }
21. }
Output:
Sonoo Jaiswal
Ankit
Peter
Irfan
1. using System;
2. using System.Collections.Generic;
3.
4. public class ListExample
5. {
6. public static void Main(string[] args)
7. {
8. // Create a list of strings using collection initializer
9. var names = new List<string>() {"Sonoo", "Vimal", "Ratan", "Love" };
10.
11. // Iterate through the list.
12. foreach (var name in names)
13. {
14. Console.WriteLine(name);
15. }
16. }
17. }
Output:
Sonoo
Vimal
Ratan
Love
C# HashSet<T>
C# HashSet class can be used to store, remove or view elements. It does not store duplicate
elements. It is suggested to use HashSet class if you have to store only unique elements. It is
found in System.Collections.Generic namespace.
C# HashSet<T> example
Let's see an example of generic HashSet<T> class that stores elements using Add() method
and iterates elements using for-each loop.
1. using System;
2. using System.Collections.Generic;
3.
4. public class HashSetExample
5. {
6. public static void Main(string[] args)
7. {
8. // Create a set of strings
9. var names = new HashSet<string>();
10. names.Add("Sonoo");
11. names.Add("Ankit");
12. names.Add("Peter");
13. names.Add("Irfan");
14. names.Add("Ankit");//will not be added
15.
16. // Iterate HashSet elements using foreach loop
17. foreach (var name in names)
18. {
19. Console.WriteLine(name);
20. }
21. }
22. }
Output:
Sonoo
Ankit
Peter
Irfan
C# SortedSet<T>
C# SortedSet class can be used to store, remove or view elements. It maintains ascending
order and does not store duplicate elements. It is suggested to use SortedSet class if you have
to store unique elements and maintain ascending order. It is found in
System.Collections.Generic namespace.
C# SortedSet<T> example
Let's see an example of generic SortedSet<T> class that stores elements using Add() method
and iterates elements using for-each loop.
1. using System;
2. using System.Collections.Generic;
3.
4. public class SortedSetExample
5. {
6. public static void Main(string[] args)
7. {
8. // Create a set of strings
9. var names = new SortedSet<string>();
10. names.Add("Sonoo");
11. names.Add("Ankit");
12. names.Add("Peter");
13. names.Add("Irfan");
14. names.Add("Ankit");//will not be added
15.
16. // Iterate SortedSet elements using foreach loop
17. foreach (var name in names)
18. {
19. Console.WriteLine(name);
20. }
21. }
22. }
Output:
Ankit
Irfan
Peter
Sonoo
C# Stack<T>
C# Stack<T> class is used to push and pop elements. It uses the concept of Stack that
arranges elements in LIFO (Last In First Out) order. It can have duplicate elements. It is
found in System.Collections.Generic namespace.
C# Stack<T> example
Let's see an example of generic Stack<T> class that stores elements using Push() method,
removes elements using Pop() method and iterates elements using for-each loop.
1. using System;
2. using System.Collections.Generic;
3.
4. public class StackExample
5. {
6. public static void Main(string[] args)
7. {
8. Stack<string> names = new Stack<string>();
9. names.Push("Sonoo");
10. names.Push("Peter");
11. names.Push("James");
12. names.Push("Ratan");
13. names.Push("Irfan");
14.
15. foreach (string name in names)
16. {
17. Console.WriteLine(name);
18. }
19.
20. Console.WriteLine("Peek element: "+names.Peek());
21. Console.WriteLine("Pop: "+ names.Pop());
22. Console.WriteLine("After Pop, Peek element: " + names.Peek());
23.
24. }
25. }
Output:
Sonoo
Peter
James
Ratan
Irfan
Peek element: Irfan
Pop: Irfan
After Pop, Peek element: Ratan
C# Queue<T>
C# Queue<T> class is used to Enqueue and Dequeue elements. It uses the concept of Queue
that arranges elements in FIFO (First In First Out) order. It can have duplicate elements. It is
found in System.Collections.Generic namespace.
C# Queue<T> example
Let's see an example of generic Queue<T> class that stores elements using Enqueue()
method, removes elements using Dequeue() method and iterates elements using for-each
loop.
1. using System;
2. using System.Collections.Generic;
3.
4. public class QueueExample
5. {
6. public static void Main(string[] args)
7. {
8. Queue<string> names = new Queue<string>();
9. names.Enqueue("Sonoo");
10. names.Enqueue("Peter");
11. names.Enqueue("James");
12. names.Enqueue("Ratan");
13. names.Enqueue("Irfan");
14.
15. foreach (string name in names)
16. {
17. Console.WriteLine(name);
18. }
19.
20. Console.WriteLine("Peek element: "+names.Peek());
21. Console.WriteLine("Dequeue: "+ names.Dequeue());
22. Console.WriteLine("After Dequeue, Peek element: " + names.Peek());
23. }
24. }
Output:
Sonoo
Peter
James
Ratan
Irfan
Peek element: Sonoo
Dequeue: Sonoo
After Dequeue, Peek element: Peter
C# LinkedList<T>
C# LinkedList<T> class uses the concept of linked list. It allows us to insert and delete
elements fastly. It can have duplicate elements. It is found in System.Collections.Generic
namespace.
C# LinkedList<T> example
Let's see an example of generic LinkedList<T> class that stores elements using AddLast()
and AddFirst() methods and iterates elements using for-each loop.
1. using System;
2. using System.Collections.Generic;
3.
4. public class LinkedListExample
5. {
6. public static void Main(string[] args)
7. {
8. // Create a list of strings
9. var names = new LinkedList<string>();
10. names.AddLast("Sonoo Jaiswal");
11. names.AddLast("Ankit");
12. names.AddLast("Peter");
13. names.AddLast("Irfan");
14. names.AddFirst("John");//added to first index
15.
16. // Iterate list element using foreach loop
17. foreach (var name in names)
18. {
19. Console.WriteLine(name);
20. }
21. }
22. }
Output:
John
Sonoo Jaiswal
Ankit
Peter
Irfan
C# Dictionary<TKey, TValue>
C# Dictionary<TKey, TValue> class uses the concept of hashtable. It stores values on the
basis of key. It contains unique keys only. By the help of key, we can easily search or remove
elements. It is found in System.Collections.Generic namespace.
Let's see an example of generic Dictionary<TKey, TValue> class that stores elements using
Add() method and iterates elements using for-each loop. Here, we are using KeyValuePair
class to get key and value.
1. using System;
2. using System.Collections.Generic;
3.
4. public class DictionaryExample
5. {
6. public static void Main(string[] args)
7. {
8. Dictionary<string, string> names = new Dictionary<string, string>();
9. names.Add("1","Sonoo");
10. names.Add("2","Peter");
11. names.Add("3","James");
12. names.Add("4","Ratan");
13. names.Add("5","Irfan");
14.
15. foreach (KeyValuePair<string, string> kv in names)
16. {
17. Console.WriteLine(kv.Key+" "+kv.Value);
18. }
19. }
20. }
Output:
1 Sonoo
2 Peter
3 James
4 Ratan
5 Irfan
C# SortedDictionary<TKey, TValue>
C# SortedDictionary<TKey, TValue> class uses the concept of hashtable. It stores values on
the basis of key. It contains unique keys and maintains ascending order on the basis of key.
By the help of key, we can easily search or remove elements. It is found in
System.Collections.Generic namespace.
Let's see an example of generic SortedDictionary<TKey, TValue> class that stores elements
using Add() method and iterates elements using for-each loop. Here, we are using
KeyValuePair class to get key and value.
1. using System;
2. using System.Collections.Generic;
3.
4. public class SortedDictionaryExample
5. {
6. public static void Main(string[] args)
7. {
8. SortedDictionary<string, string> names = new SortedDictionary<string, string>()
;
9. names.Add("1","Sonoo");
10. names.Add("4","Peter");
11. names.Add("5","James");
12. names.Add("3","Ratan");
13. names.Add("2","Irfan");
14. foreach (KeyValuePair<string, string> kv in names)
15. {
16. Console.WriteLine(kv.Key+" "+kv.Value);
17. }
18. }
19. }
Output:
1 Sonoo
2 Irfan
3 Ratan
4 Peter
5 James
C# SortedList<TKey, TValue>
C# SortedList<TKey, TValue> is an array of key/value pairs. It stores values on the basis of
key. The SortedList<TKey, TValue> class contains unique keys and maintains ascending
order on the basis of key. By the help of key, we can easily search or remove elements. It is
found in System.Collections.Generic namespace.
Let's see an example of generic SortedList<TKey, TValue> class that stores elements using
Add() method and iterates elements using for-each loop. Here, we are using KeyValuePair
class to get key and value.
1. using System;
2. using System.Collections.Generic;
3.
4. public class SortedDictionaryExample
5. {
6. public static void Main(string[] args)
7. {
8. SortedList<string, string> names = new SortedList<string, string>();
9. names.Add("1","Sonoo");
10. names.Add("4","Peter");
11. names.Add("5","James");
12. names.Add("3","Ratan");
13. names.Add("2","Irfan");
14. foreach (KeyValuePair<string, string> kv in names)
15. {
16. Console.WriteLine(kv.Key+" "+kv.Value);
17. }
18. }
19. }
Output:
1 Sonoo
2 Irfan
3 Ratan
4 Peter
5 James
ArrayList:
Hashtable:
SortedList:
Queue:
Stack:
// Producer
Task.Factory.StartNew(() =>
{
for (int i = 0; i < 10; i++)
{
blockingCollection.Add(i);
Console.WriteLine($"Produced: {i}");
}
blockingCollection.CompleteAdding();
});
// Consumer
Task.Factory.StartNew(() =>
{
while (!blockingCollection.IsCompleted)
{
if (blockingCollection.TryTake(out int item))
{
Console.WriteLine($"Consumed: {item}");
}
}
});
Task.WaitAll();
}
}
2. ConcurrentQueue<T>: Represents a thread-safe first-in, first-out (FIFO) collection.
// Enqueue (Producer)
Parallel.For(0, 10, i =>
{
concurrentQueue.Enqueue(i);
Console.WriteLine($"Enqueued: {i}");
});
// Dequeue (Consumer)
Parallel.For(0, 10, i =>
{
if (concurrentQueue.TryDequeue(out int item))
{
Console.WriteLine($"Dequeued: {item}");
}
});
These examples demonstrate how to use some of the concurrent collection classes in C# for
multi-threaded scenarios. They help ensure thread safety and avoid common issues associated
with concurrent access to shared data.