Page 109 - CSharp/C#
P. 109
Usage:
int[] sequence = Enumerable.Range(1, 100).ToArray();
This will generate an array containing the numbers 1 through 100 ([1, 2, 3, ..., 98, 99, 100]).
Because the Range method returns an IEnumerable<int>, we can use other LINQ methods on it:
int[] squares = Enumerable.Range(2, 10).Select(x => x * x).ToArray();
This will generate an array that contains 10 integer squares starting at 4: [4, 9, 16, ..., 100, 121]
.
Comparing arrays for equality
LINQ provides a built-in function for checking the equality of two IEnumerables, and that function
can be used on arrays.
The SequenceEqual function will return true if the arrays have the same length and the values in
corresponding indices are equal, and false otherwise.
int[] arr1 = { 3, 5, 7 };
int[] arr2 = { 3, 5, 7 };
bool result = arr1.SequenceEqual(arr2);
Console.WriteLine("Arrays equal? {0}", result);
This will print:
Arrays equal? True
Arrays as IEnumerable<> instances
All arrays implement the non-generic IList interface (and hence non-generic ICollection and
IEnumerable base interfaces).
More importantly, one-dimensional arrays implement the IList<> and IReadOnlyList<> generic
interfaces (and their base interfaces) for the type of data that they contain. This means that they
can be treated as generic enumerable types and passed in to a variety of methods without
needing to first convert them to a non-array form.
int[] arr1 = { 3, 5, 7 };
IEnumerable<int> enumerableIntegers = arr1; //Allowed because arrays implement IEnumerable<T>
List<int> listOfIntegers = new List<int>();
listOfIntegers.AddRange(arr1); //You can pass in a reference to an array to populate a List.
After running this code, the list listOfIntegers will contain a List<int> containing the values 3, 5,
and 7.
https://riptutorial.com/ 55

