In this post I will cover how to declare, initialize, access and use LINQ with arrays in C#.
Declaring arrays
Arrays in C# are declared in the following way:
DataType [] nameOfArray
So, if we want to declare an int array called numbers
, we would do the following:
int [] numbers;
We can also use the keyword var
and let the compiler determine the data type of the array based on the data type of the values the array is initialized with or contains.
var [] numbers;
Invalid ways to declare an array
Arrays must be initialized with a size, you cannot initialize an array in C# like the following:
Not specifying a size
int[] numbers = new int[]; //Wrong
The number of elements do not equal the size of the array when initializing an array
int[] numbers = new int[3] {1, 2};
Initializing an array using var
var numbers = {1, 2, 3};
Initializing arrays
There are two ways to initialize arrays: instant initialization and late initialization. We do either of those in the following manner:
Instant initialization
int[] numbers = new int[3];
Adding initial values to the array:
int[] numbers = new int[3] {1, 2, 3};
Using shorthand:
int[] numbers = {1, 2, 3};
Late initialization
int[] numbers;
numbers = new int[3];
OR
numbers = new int[3] {1, 2, 3};
Accessing arrays
We can access arrays by using the following structure:
nameOfArray[index];
In order to access the number 3 from the numbers array above, we would do the following:
Console.WriteLine(numbers[2]); //3
3 is at position 2 in the array since the index of the array starts at 0.
Using LINQ with arrays
LINQ is an abbreviation for Language Integrated Query. It is used for querying data but can also be used for extracting data from different data structures, such as arrays. The LINQ methods that are available for arrays are implemented through the interface IEnumerable
. LINQ methods such as Min()
, Max()
, Sum()
, and Average()
.
int[] numbers = new int[3] {1, 2, 3};
numbers.Min(); //1
numbers.Max(); //3
numbers.Sum(); //6
numbers.Average(); //2