Loops and Collections

Loops & Collections

Loops:

Loops in C# are control structures that allow repeating a block of code multiple times. Loops are fundamental for controlling execution flow in a program. Here's a description of the most common types of loops in C# along with examples:

While loop:

  • The while loop executes as long as a condition is true. It's important to ensure that the condition changes at some point to avoid an infinite loop.

int counter = 0;
while (counter < 5)
{
    Console.WriteLine("Iteration " + counter);
    counter++;
}

Do-while loop:

  • The do-while loop is similar to while, but guarantees that the code block executes at least once before checking the condition.

int number = 5;
do
{
    Console.WriteLine("Number equals " + number);
    number--;
} while (number > 0);

For loop:

  • The for loop is useful when you know in advance the number of iterations needed. It includes an initialization, a condition, and an increment expression.

💡 Besides doing it incrementally, you can also do it decrementally!


Foreach loop:

  • The foreach loop is mainly used to iterate through elements of a collection, such as arrays or lists. (In a minute you'll know what a list or array is)


Break and continue loops:

  • You can use the break statement to exit a loop before the condition is met and continue to skip the current iteration and move to the next one.


Collections:

Collections in C# are data structures that allow storing and manipulating sets of elements. Here's a description of the most common types of collections in C# along with examples:

Array[]

  • An array is a collection of elements of the same type with a fixed size that is declared at compile time.

Array declaration:

  • To declare an array, you can use the following syntax:

Array initialization:

  • You can initialize an array with values at the moment of declaration:

Element access:

  • To access array elements, you can use the index in brackets:

Array length:

  • You can get the length of an array using the Length property:

Clone an array:

  • You can create a copy of an array using the Clone() method:

Sort an array:

  • You can sort an array using the Array.Sort() method:

Search for an element in an array:

  • You can search for an element in an array using the Array.IndexOf() method:

Traverse an array:

  • You can traverse an array using loops like for or foreach (as we saw in the previous section).

Keep in mind that if you need to add or remove elements from a collection dynamically, you might want to consider using other data structures like List<T> instead of arrays, since lists allow more flexible operations for inserting and removing elements.


List<>

  • A list is a dynamic collection that can grow or shrink in size as needed.

Add elements to a list:

  • You can add elements to a list using the Add() method:

Access list elements:

  • To access list elements, you can use the index in brackets, just like with arrays:

Overwrite list elements:

  • You can overwrite an existing element in a list using the index:

Get the length of a list:

  • You can get the number of elements in a list using the Count property: (Be careful, it's not like arrays where Length is used)

Clone a list:

  • You can create a copy of a list using the List<T> constructor that takes another list as an argument:

Sort a list:

  • You can sort a list using the Sort() method:

Search for an element in a list:

  • You can search for an element in a list using the IndexOf() method:

Remove elements from a list:

  • You can remove elements from a list using methods like Remove(), RemoveAt(), or RemoveAll():

Traverse a list:

  • You can traverse a list using loops like for or foreach just like with arrays.


Dictionary

Dictionaries in C# are a data structure that stores key-value pairs, where each key is unique. Here's a description of the most common operations you can perform with a Dictionary<TKey, TValue> in C#, along with examples:

Dictionary declaration and initialization:

  • You can declare and initialize a dictionary as follows:

Add elements to a dictionary:

  • You can add key-value pairs to a dictionary using the Add() method:

Access dictionary values:

  • To access dictionary values, you can use the key as an index:

Keep in mind that if the key doesn't exist in the dictionary, this will throw a KeyNotFoundException. To avoid this, you can use the TryGetValue() method:

Check if a key exists in a dictionary:

  • You can check if a key exists in a dictionary using the ContainsKey() method:

Remove elements from a dictionary:

  • You can remove elements from a dictionary using the Remove() method:

Clear a dictionary:

  • You can remove all elements from a dictionary using the Clear() method:

Get the number of elements in a dictionary:

  • You can get the number of elements in a dictionary using the Count property:

Traverse a dictionary:

  • You can traverse a dictionary using a foreach loop or access its keys or values using the Keys and Values properties. Same as with arrays and Lists but keeping in mind that you handle 2 values.

Dictionaries (Dictionary<TKey, TValue>) are ideal when you need to associate values with unique keys and perform efficient searches. They are a fundamental data structure in programming and are widely used in many applications.


Other collections:

While the most common is to use Array, List and Dictionary. There are other types of very useful collections that have other uses. I'm not going to go deep into them now because it would be too much data all at once. But it is important that you read them to know they exist and if you ever have to do something similar you can google how to use them and what they do.

Tuple:

  • A tuple is an ordered collection of elements of different types. It's used when you need a simple data structure to store related values. Unlike Dictionary, the tuple can store 2 or more equal keys. Because they're not keys.


HashSet:

  • A set (HashSet) is a collection that stores unique elements without duplicates. It's useful when you need to guarantee that there are no repeated elements. It's the opposite of a Dictionary where instead of not being able to have 2 equal keys. You can't have 2 equal values.


Stack:

  • A stack is a collection that follows the LIFO principle (last in, first out). It's used to store elements that must be processed in reverse order. It can be used perfectly in a deck of cards. Because the first one you add will be the last one to come out.


Queue:

  • A queue is a collection that follows the FIFO principle (first in, first out). It's used to store elements that must be processed in the order they were added, similar to a line in real life. (The opposite of Stack)

In the example, clients are added to the queue in order. When Dequeue() is called, the first client who arrived at the queue is removed and returned, which in this case is "Client1". This ensures that elements are handled in the same order they were added, which is useful in situations where it's important to maintain a specific order, such as task or process management in a system.


Last updated