text
stringlengths
0
13.4k
Console.WriteLine(sumOfAllNumbers); //10
var cities = new[] {
new {Population = 1000},
new {Population = 2500},
new {Population = 4000}
};
var totalPopulation = cities.Sum(c => c.Population);
Console.WriteLine(totalPopulation); //7500
Section 8.13: SequenceEqual
var numbers = new[] {1,2,3,4,5};
var sameNumbers = new[] {1,2,3,4,5};
var sameNumbersInDifferentOrder = new[] {5,1,4,2,3};
var equalIfSameOrder = numbers.SequenceEqual(sameNumbers);
Console.WriteLine(equalIfSameOrder); //True
var equalIfDifferentOrder = numbers.SequenceEqual(sameNumbersInDifferentOrder);
Console.WriteLine(equalIfDifferentOrder); //False
Section 8.14: Min
var numbers = new[] {1,2,3,4};
var minNumber = numbers.Min();
Console.WriteLine(minNumber); //1
var cities = new[] {
new {Population = 1000},
new {Population = 2500},
new {Population = 4000}
};
var minPopulation = cities.Min(c => c.Population);
Console.WriteLine(minPopulation); //1000
GoalKicker.com – .NET Framework Notes for Professionals
33
Section 8.15: Distinct
var numbers = new[] {1, 1, 2, 2, 3, 3, 4, 4, 5, 5};
var distinctNumbers = numbers.Distinct();
Console.WriteLine(string.Join(",", distinctNumbers));
//1,2,3,4,5
Section 8.16: Count
IEnumerable<int> numbers = new[] {1,2,3,4,5,6,7,8,9,10};
var numbersCount = numbers.Count();
Console.WriteLine(numbersCount); //10
var evenNumbersCount = numbers.Count(n => (n & 1) == 0);
Console.WriteLine(evenNumbersCount); //5
Section 8.17: Cast
Cast is different from the other methods of Enumerable in that it is an extension method for IEnumerable, not for
IEnumerable<T>. Thus it can be used to convert instances of the former into instances of the later.
This does not compile since ArrayList does not implement IEnumerable<T>:
var numbers = new ArrayList() {1,2,3,4,5};
Console.WriteLine(numbers.First());
This works as expected:
var numbers = new ArrayList() {1,2,3,4,5};
Console.WriteLine(numbers.Cast<int>().First()); //1
Cast does not perform conversion casts. The following compiles but throws InvalidCastException at runtime:
var numbers = new int[] {1,2,3,4,5};
decimal[] numbersAsDecimal = numbers.Cast<decimal>().ToArray();
The proper way to perform a converting cast to a collection is as follows:
var numbers= new int[] {1,2,3,4,5};
decimal[] numbersAsDecimal = numbers.Select(n => (decimal)n).ToArray();
Section 8.18: Range
The two parameters to Range are the first number and the count of elements to produce (not the last number).
// prints 1,2,3,4,5,6,7,8,9,10
Console.WriteLine(string.Join(",", Enumerable.Range(1, 10)));
// prints 10,11,12,13,14
Console.WriteLine(string.Join(",", Enumerable.Range(10, 5)));
GoalKicker.com – .NET Framework Notes for Professionals