Collections in C# Language
In C#, collections are an essential part of any developer’s toolkit. They provide a way to store and m
anipulate groups of data, making it easier to manage, access, and manipulate information in your applications. In this post, we’ll explore some of the most commonly used collection types in C# and provide examples of how to work with them.Arrays
Arrays are one of the simplest and most widely used collection types in C#. They are a fixed-size collection of elements of the same type.
int[] numbers = new int[5] { 1, 2, 3, 4, 5 };
Lists
Lists are dynamic arrays in C# that can grow or shrink in size. They are part of the System.Collections.Generic
namespace.
List<string> names = new List<string>() { "Alice", "Bob", "Charlie" };
names.Add("David");
Dictionaries
Dictionaries are key-value pairs where each key maps to a value. They are also part of the System.Collections.Generic
namespace.
Dictionary<string, int> ageLookup = new Dictionary<string, int>();
ageLookup["Alice"] = 25;
ageLookup["Bob"] = 30;
Sets
Sets are collections that contain unique elements. Duplicates are automatically eliminated.
HashSet<int> uniqueNumbers = new HashSet<int>() { 1, 2, 3, 3, 4, 5 };
Queues
Queues are used to manage a first-in, first-out (FIFO) collection of items.
Queue<string> queue = new Queue<string>();
queue.Enqueue("First");
queue.Enqueue("Second");
string item = queue.Dequeue(); // "First"
Stacks
Stacks are used to manage a last-in, first-out (LIFO) collection of items.
Stack<string> stack = new Stack<string>();
stack.Push("First");
stack.Push("Second");
string item = stack.Pop(); // "Second"
Collections in LINQ
C# also provides Language-Integrated Query (LINQ) for querying and manipulating collections. LINQ allows you to perform powerful operations on collections, such as filtering, sorting, and projection.
List<int> numbers = new List<int>() { 1, 2, 3, 4, 5 };
var evenNumbers = numbers.Where(x => x % 2 == 0).ToList();
Discover more from PiEmbSysTech
Subscribe to get the latest posts sent to your email.