[go: up one dir, main page]

0% found this document useful (0 votes)
42 views17 pages

Collection C#

The document discusses different collection types in C# including List, Stack, Queue, Dictionary, SortedList, ArrayList, Hashtable, and Concurrent collections. It describes their characteristics and provides code examples to demonstrate adding and iterating over elements in List, HashSet, SortedSet, and Stack collections.

Uploaded by

Sonam Pandey
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views17 pages

Collection C#

The document discusses different collection types in C# including List, Stack, Queue, Dictionary, SortedList, ArrayList, Hashtable, and Concurrent collections. It describes their characteristics and provides code examples to demonstrate adding and iterating over elements in List, HashSet, SortedSet, and Stack collections.

Uploaded by

Sonam Pandey
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

C# Collections

Problem with Array

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

In sort, all the data structure work can be performed by C# collections.

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

The System.Collections.Generic classes help us to create a generic collection. In this, we


store type compatible data elements. This collection does not allow us to store different types
of elements.
Let's take an example of a generic class: List<T>.
using System;
using System.Collections.Generic;

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]); //
}
}

The above code throws the following error:

Argument 1: cannot convert from 'string' to 'int'

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:

 Push()- insert elements


 Pop()- remove elements

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>

The Dictionary<TKey, TValue> is a generic collection that stores key-value pairs in no


particular order.

Dictionary Characteristics

 Dictionary<TKey, TValue> stores key-value pairs.

 Comes under System.Collections.Generic namespace.

 Implements IDictionary<TKey, TValue> interface.

 Keys must be unique and cannot be null.

 Values can be null or duplicate.

 Values can be accessed by passing associated key in the indexer


e.g. myDictionary[key]

 Elements are stored as KeyValuePair<TKey, TValue> objects.

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

The System.Collections.Concurrent provides some collection classes that help to achieve


thread-safe code.

What is Thread Safety?

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>

Basic Operations on List


The List<T> class provides various methods to perform different operations on List. We will
look at some commonly used List operations in this tutorial:
 Add Elements
 Insert Elements
 Remove Elements

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

C# List<T> example using collection initializer

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.

It allows us to add and remove element at before or last index.

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.

C# Dictionary<TKey, TValue> example

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.

C# SortedDictionary<TKey, TValue> example

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.

It is like SortedDictionary<TKey, TValue> class.


C# SortedList<TKey, TValue> vs SortedDictionary<TKey, TValue>

SortedList<TKey, TValue> class uses less memory than SortedDictionary<TKey, TValue>.


It is recommended to use SortedList<TKey, TValue> if you have to store and retrieve
key/valye pairs. The SortedDictionary<TKey, TValue> class is faster than SortedList<TKey,
TValue> class if you perform insertion and removal for unsorted data.

C# SortedList<TKey, TValue> example

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

System.Collections Classes/Non Generics

ArrayList:

System.Collections.ArrayList is a dynamic array that can hold elements of any type.


ArrayList list = new ArrayList();
list.Add(10);
list.Add("Hello");
list.Add(DateTime.Now);
foreach (var item in list)
{
Console.WriteLine(item);
}

Hashtable:

System.Collections.Hashtable is a collection of key/value pairs, where keys and values can be


of any type.

Hashtable hashtable = new Hashtable();


hashtable.Add("Name", "John");
hashtable.Add("Age", 25);
hashtable.Add("IsStudent", true);

foreach (DictionaryEntry entry in hashtable)


{
Console.WriteLine($"{entry.Key}: {entry.Value}");
}

SortedList:

System.Collections.SortedList is a collection of key/value pairs sorted by the keys.

SortedList sortedList = new SortedList();


sortedList.Add("Bob", 30);
sortedList.Add("Alice", 25);
sortedList.Add("Eva", 28);

foreach (DictionaryEntry entry in sortedList)


{
Console.WriteLine($"{entry.Key}: {entry.Value}");
}

Queue:

System.Collections.Queue represents a first-in, first-out (FIFO) collection of objects.


Queue queue = new Queue();
queue.Enqueue("Item 1");
queue.Enqueue("Item 2");
queue.Enqueue("Item 3");

while (queue.Count > 0)


{
Console.WriteLine(queue.Dequeue());
}

Stack:

System.Collections.Stack represents a last-in, first-out (LIFO) collection of objects.


Stack stack = new Stack();
stack.Push("Item 1");
stack.Push("Item 2");
stack.Push("Item 3");

while (stack.Count > 0)


{
Console.WriteLine(stack.Pop());
}

In C#, the System.Collections.Concurrent namespace provides a set of collection classes that


are designed for safe and efficient multi-threaded operations. These classes are particularly
useful in scenarios where multiple threads need to access and modify shared data. Here are
some of the key classes in this namespace along with a simple example:

1. BlockingCollection<T>: Provides a blocking version of a collection, which means


that it will block or wait until an operation can be completed.

BlockingCollection<int> blockingCollection = new BlockingCollection<int>();

// 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.

ConcurrentQueue<int> concurrentQueue = new ConcurrentQueue<int>();

// 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}");
}
});

3. ConcurrentDictionary<TKey, TValue>: Represents a thread-safe collection of


key/value pairs that can be accessed by multiple threads.

ConcurrentDictionary<int, string> concurrentDictionary = new


ConcurrentDictionary<int, string>();

// Add items (Producer)


Parallel.For(0, 10, i =>
{
concurrentDictionary.TryAdd(i, $"Value-{i}");
Console.WriteLine($"Added: {i}");
});

// Retrieve items (Consumer)


Parallel.ForEach(concurrentDictionary, kvp =>
{
Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
});

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.

You might also like