Collections in C#
Collections can be defined as a type of class used in C# for dynamic memory allocation for storing and fetching of the contents of the class, and can be used for performing multiple operations. In C#, the collections work in the form of ‘System.Collections.Generic classes’, ‘System.Collections. Concurrent classes’ and ‘System.Collections classes’. In terms of storage patterns, collections replicate the data structure of an Array, and the only difference is, unlike arrays, collections doesn’t need to be defined with the size required.
There are 3 ways to work with collections which are follow
- System.Collections.Generic classes
- System.Collections.Concurrent classes
- System.Collections classes
Examples of Collections in C#
Below are some examples of various type of collection in C#:-
Example #1 – ArrayList
It is a collection of System.Collections. It allows to hold the data of multiple data types and as the data is added, it expands automatically.
Code:
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ArrayListExample { class Program { static void Main(string[] args) { var data = new ArrayList(); //arraylist collection data.Add("Demo"); // add element data.Add(1); data.Add(5); data.Add(26); data.Add(56.4); data.Add(32); data.Remove(5); // remove element foreach (object obj in data) // iteration { Console.WriteLine(obj); Console.ReadLine(); } } } }
In the above example, there is a collection of type ArrayList. There are some elements in ArrayList. Add() and Remove() are the methods which is used to add and remove the elements from collection respectively. foreach is used for the iteration and display the values.
Output:
Example# 2 – We will use list operation here
It is a collection of System.Collections.Generic namespace.
Code:
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Collections { class Program { static void Main(string[] args) { var value = new List<string>(); // list collection value.Add("Cricket"); // add element value.Add("Football"); value.Add("Volleyball"); value.Add("Hockey"); value.Add("Basketball"); value.Add("Tennis"); value.Remove("Football"); // remove element value.Remove("Tennis"); value.Insert(3, "Badminton"); // insert element foreach (string st in value) { Console.WriteLine(st); Console.ReadLine(); } } } }
In the above example, the collection is of a list type. Add() and Remove() methods are used to add or remove the elements from the list respectively. Insert() is also used to insert the element in the list at a defined index. Foreach is used for iteration and display the values.
Output:
Example# 3 : Sorted List
It consists of key and values in a collection.
Code:
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Collections { class Program { static void Main(string[] args) { var value = new SortedList<string, int>(); // sortedlist collection value.Add("java", 3); // add element value.Add("javascript", 4); value.Add("c-sharp", 5); value.Add("dotnet", 25); value.Add("python", 27); value.Add("typescript", 57); foreach (var pair in value) { Console.WriteLine(pair); Console.ReadLine(); } } } }
In the above example, collection is of type sortedlist. There are multiple pairs of key and values in the list. It basically represents the sorted pair of keys and values.
Output:
Example# 4 : Linked list
It basically allows the sequential access of the elements.
Code:
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Collections { class Program { static void Main(string[] args) { var value = new LinkedList<int>(); // linkedlist collection value.AddLast(13); // add element value.AddLast(33); value.AddLast(23); value.AddLast(51); value.AddLast(60); value.AddFirst(4); value.AddFirst(6); LinkedListNode<int> node = value.Find(51); // find the node value.AddBefore(node, 40); foreach (int num in value) { Console.WriteLine(num); Console.ReadLine(); } } } }
In the above example, collection is of type Linkedlist. AddLast() is used to place the element in the last postion whereas AddFirst() is used to place the element at first position of the list. Linkedlist consists of a node. Find() is used to find the value and place value before it.
Output :
Example# 5 – Dictionary
It consists of unique pair of keys and values.
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Collections { class Program { static void Main(string[] args) { var pair = new Dictionary<string, string>(); // dictionary collection pair.Add("in", "India"); // add keys and values pair.Add("af", "Africa"); pair.Add("us", "United States"); pair.Add("ja", "Japan"); pair.Add("ch", "China"); pair.Add("ca", "Canada"); Console.WriteLine("Keys present in the dictionary:"); var key = new List<string>(pair.Keys); foreach (string k in key) { Console.WriteLine("{0}", k); } Console.WriteLine("Values present in the dictionary:"); var value = new List<string>(pair.Values); foreach (string val in value) { Console.WriteLine("{0}", val); } Console.ReadLine(); } } }
In above example, collection is of type dictionary which contains key and their values. Foreach is used for the iteration of keys and values.
Output
Example# 6 – Stack
It is based on the Last-In-First-Out structure. The last element of the queue is the first one to be removed.
Code:
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Collections { class Program { static void Main(string[] args) { var value = new Stack<int>(); // stack collection value.Push(10); // adding the element value.Push(40); value.Push(33); value.Push(62); value.Push(48); value.Push(21); value.Push(31); Console.WriteLine(value.Pop()); Console.WriteLine(value.Peek()); Console.WriteLine(); foreach (int item in value) { Console.WriteLine(item); Console.ReadLine(); } } } }
In the above example, collection is of type stack. Push() is used to inserting the element at the top. Pop() is for removing and returning the element and Peek() is for returning the top element of the stack.
Output:
Example# 7 – Queue
It is based on First-In-First-Out structure. The first element of the queue is the first one to be removed.
Code:
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Collections { class Program {static void Main(string[] args) { var value = new Queue<string>(); // queue collection value.Enqueue("Item 1"); // add element value.Enqueue("Item 2"); value.Enqueue("Item 3"); value.Enqueue("Item 4"); value.Enqueue("Item 5"); value.Enqueue("Item 6"); value.Enqueue("Item 7"); Console.WriteLine(value.Dequeue()); Console.WriteLine(value.Peek()); Console.WriteLine(); foreach (string num in value) { Console.WriteLine(num); Console.ReadLine(); } } } }
In the above example; collection is of type queue. Enqueue() is for the inserting element at the end of the queue. Dequeue() is for removing the element from the beginning of the queue. Peek() is used for returning the item.
Output:
So there are many ways we can use the collections. Collections are similar to an array. Here we don’t need to define the size beforehand unlike array.
The above is the detailed content of Collections in C#. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

Guide to Factorial in C#. Here we discuss the introduction to factorial in c# along with different examples and code implementation.

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

Guide to Prime Numbers in C#. Here we discuss the introduction and examples of prime numbers in c# along with code implementation.

There are several ways to modify XML formats: manually editing with a text editor such as Notepad; automatically formatting with online or desktop XML formatting tools such as XMLbeautifier; define conversion rules using XML conversion tools such as XSLT; or parse and operate using programming languages such as Python. Be careful when modifying and back up the original files.
