C# Basics/
Arrays and lists
This page have a related YouTube video
- Declaring and Initializing Arrays and Lists
- Accessing and Modifying Elements in Arrays and Lists
- Iterating Over Arrays and Lists
- Sorting and Searching Arrays and Lists
- Resizing and Reshaping Arrays and Lists
- Converting between Arrays and Lists
- Multidimensional Arrays
- Collection Classes
The differences between Arrays and Lists
C# arrays and lists are both used to store collections of data, but they have some key differences.
Arrays are a fixed size, meaning that once an array is created, its size cannot be changed. Lists, on the other hand, are dynamic, meaning that elements can be added or removed from a list as needed.
Arrays are also more efficient for certain operations, such as accessing elements by index, because the elements are stored in contiguous memory locations. Lists, however, can be slower for these operations because the elements are stored in a linked list structure.
Additionally, arrays support the concept of multidimensional arrays, while lists do not.
In summary, arrays are best used when the size of the collection is known in advance and performance is a concern, while lists are more flexible and can be used when the size of the collection may change.
Declaring and Initializing Arrays and Lists
In C#, arrays and lists are used to store collections of data. Both arrays and lists are zero-based, meaning that the first element is at index 0.
Here's an example of declaring and initializing an array in C#:
In the example above, we first declared an array of integers with a size of 3. We then assigned values to each element of the array using the [] operator.
You can also declare and initialize an array in a single line of code:
In this way of declaring an array, the size of the array is determined by the number of elements we put in it.
Lists are similar to arrays, but they are part of the System.Collections.Generic
namespace and can be resized as needed. Here's an example of declaring and initializing a list in C#:
In this example, we declared a List of integers, and then added elements to the list using the Add()
method.
You can also initialize a list with values by using the List
constructor:
As you can see, declaring and initializing arrays and lists in C# is straightforward, and both have their use cases. Knowing when to use an array or a list depends on the size and structure of your data, as well as the functional requirements of your application.
Accessing and Modifying Elements in Arrays and Lists
Once you've declared and initialized an array or list, you can access and modify the elements in several ways.
Accessing Elements
In C#, you can access an element of an array or a list using its index, like this:
In addition to accessing elements by index, C# also provides the foreach
loop for iterating through the elements of an array or list:
Modifying Elements
In C#, you can modify an element of an array or a list by assigning a new value to it using its index, like this:
You can also use the List
class' RemoveAt()
method to remove an element of a list by index, and Insert()
method to insert a new element to a specific index.
You can also use the Array
class' Sort()
method to sort the elements in an array and IndexOf()
method to find the index of a specific element in an array.
It's important to note that when you try to access or modify an element of an array or list using an index that is outside its range, you will get an "IndexOutOfRangeException" exception, so it's important to always check the range of the index before you try to access or modify an element.
Iterating Over Arrays and Lists
In C#, there are several ways to iterate over the elements of an array or a list.
For Loop
One way to iterate over an array is to use a for loop. The for loop allows you to specify a starting point, an ending point, and a way to increment or decrement the loop variable.
Foreach Loop
Another way to iterate over an array or a list is to use the foreach loop. The foreach loop allows you to iterate over the elements of a collection without having to worry about the index or the number of elements.
Using enumerator
You can also use the enumerator provided by the Array and List classes to iterate over their elements.
You can choose the method that best suits your needs and the structure of your code.
Sorting and Searching Arrays and Lists
Sorting and searching are two common operations that are performed on arrays and lists. C# provides several built-in methods for sorting and searching the elements of an array or list.
Sorting Arrays and Lists
To sort the elements of an array or list, you can use the Array.Sort() or List.Sort() method. Here's an example of using the Array.Sort() method to sort the elements of an array:
In this example, the Array.Sort() method is used to sort the elements of the "numbers" array in ascending order. After sorting, the elements of the array will be [1, 2, 3, 4, 5]. The foreach loop is used to print the sorted array.
The List.Sort() method can be used in a similar way to sort the elements of a list:
In this example, the List.Sort() method is used to sort the elements of the "names" list in ascending order. After sorting, the elements of the list will be ["Alice", "Bob", "Charlie"]. The foreach loop is used to print the sorted list.
Searching Arrays and Lists
To search for a specific element in an array or list, you can use the Array.BinarySearch() or List.BinarySearch() method. Here's an example of using the Array.BinarySearch() method to search for an element in an array:
In this example, the Array.BinarySearch() method is used to search for the number 3 in the "numbers" array. If the element is found, the method returns the index of the element in the array. If the element is not found, the method returns a negative value. In this case, the element 3 is found at index 2. The if-else statement is used to check the result of the search and print the appropriate message to the console.
The List.BinarySearch() method can be used in a similar way to search for an element in a list:
In this example, the List.BinarySearch() method is used to search for the string "Bob" in the "names" list. If the element is found, the method returns the index of the element in the list. If the element is not found, the method returns a negative value. In this case, the element "Bob" is found at index 1. The if-else statement is used to check the result of the search and print the appropriate message to the console.
Note that both the Array.Sort() and List.Sort() methods should be called before using the Array.BinarySearch() and List.BinarySearch() methods, respectively, as these methods use the binary search algorithm, which requires the array or list to be sorted first.
Resizing and Reshaping Arrays and Lists
In some cases, you may need to resize or reshape an array or list after it has been created. C# provides several built-in methods for resizing and reshaping arrays and lists.
Resizing Arrays
To resize an array, you can use the Array.Resize() method. Here's an example of using the Array.Resize() method to increase the size of an array:
In this example, the Array.Resize() method is used to increase the size of the "numbers" array from 3 to 5. The foreach loop is used to print the elements of the resized array, which will now include two additional elements with the default value of 0.
Note that the Array.Resize() method can also be used to decrease the size of an array, in which case the extra elements will be truncated.
Reshaping Lists
To reshape a list, you can use the List.Add() and List.Remove() methods. Here's an example of using the List.Add() method to add an element to a list:
In this example, the List.Add() method is used to add the string "Charlie" to the "names" list. The foreach loop is used to print the elements of the reshaped list, which will now include the additional element "Charlie".
To remove an element from a list, you can use the List.Remove() method. Here's an example of using the List.Remove() method to remove an element from a list:
In this example, the List.Remove() method is used to remove the string "Bob" from the "names" list. The foreach loop is used to print the elements of the reshaped list, which will no longer include the element "Bob".
Converting between Arrays and Lists
In some cases, you may need to convert an array to a list or a list to an array. C# provides several built-in methods for converting between arrays and lists.
Converting an Array to a List
To convert an array to a list, you can use the Array.ToList() method. Here's an example of using the Array.ToList() method to convert an array to a list:
In this example, the Array.ToList() method is used to convert the "numbers" array to a list. The foreach loop is used to print the elements of the list.
Converting a List to an Array
To convert a list to an array, you can use the List.ToArray() method. Here's an example of using the List.ToArray() method to convert a list to an array:
In this example, the List.ToArray() method is used to convert the "names" list to an array. The foreach loop is used to print the elements of the array.
Multidimensional Arrays
In C#, arrays can have multiple dimensions. A multidimensional array is an array that contains one or more arrays as its elements. There are two types of multidimensional arrays in C#: rectangular arrays and jagged arrays.
Rectangular Arrays
A rectangular array is a multidimensional array that has a uniform number of elements in each dimension. The syntax for declaring a two-dimensional rectangular array is as follows:
Here's an example of how to initialize a 2-dimensional rectangular array:
In this example, the array "numbers" is a 2-dimensional rectangular array with 3 rows and 2 columns. The nested for loop is used to print the elements of the array. The GetLength() method is used to get the number of rows and columns in the array.
Jagged Arrays
A jagged array is a multidimensional array that has a different number of elements in each dimension. The syntax for declaring a jagged array is as follows:
Here's an example of how to initialize a 2-dimensional jagged array:
In this example, the array "numbers" is a 2-dimensional jagged array with 3 rows. Each row has a different number of columns. The nested for loop is used to print the elements of the array. The Length property is used to get the number of rows and columns in the array.
Collection Classes
In C#, there are several built-in collection classes that provide additional functionality beyond what is offered by arrays and lists. These classes include the Stack, Queue, and Dictionary classes, among others.
Stack
A Stack is a last-in, first-out (LIFO) data structure. It can be used to add and remove elements in a specific order. The Stack class provides several methods such as Push, Pop, Peek, etc. Here's an example of using the Stack class:
In this example, the Stack class is used to create a stack of integers. The Push method is used to add elements to the stack, the Pop method is used to remove the last element from the stack and returns it and the Peek method is used to return the last element of the stack without removing it.
Queue
A Queue is a first-in, first-out (FIFO) data structure. It can be used to add and remove elements in a specific order . The Queue class provides several methods such as Enqueue, Dequeue, Peek, etc. Here's an example of using the Queue class:
In this example, the Queue class is used to create a queue of strings. The Enqueue method is used to add elements to the queue, the Dequeue method is used to remove the first element from the queue and returns it, and the Peek method is used to return the first element of the queue without removing it.
Dictionary
A Dictionary is a collection of key-value pairs. It can be used to store, retrieve and remove elements. The Dictionary class provides several methods such as Add, Remove, ContainsKey, etc. Here's an example of using the Dictionary class:
In this example, the Dictionary class is used to create a dictionary of strings and integers. The Add method is used to add elements to the dictionary, where the first parameter is the key and the second parameter is the value. The key is used to retrieve the value from the dictionary. The Remove method is used to remove elements from the dictionary, and the ContainsKey method is used to check if a key exists in the dictionary.
These collection classes provide a more robust way of storing and manipulating data compared to arrays and lists. They can be used in a variety of situations where more advanced data structures are required.