C# 4.0. How can the following be done using lambda expressions?
int[] a = new int[8] { 0, 1, 2, 3, 4, 5, 6, 7 };
// Now fetch every second element so that we get { 0, 2, 4, 6 }
C# 4.0. How can the following be done using lambda expressions?
int[] a = new int[8] { 0, 1, 2, 3, 4, 5, 6, 7 };
// Now fetch every second element so that we get { 0, 2, 4, 6 }
int[] list = a.Where((value, index) => index % 2 == 0)
.ToArray();
It will only select even indexes, as calculate by the %
(mod) operator .
5 % 2 // returns 1
4 % 2 // returns 0
According to MSDN:
Another approach using Enumerable.Range
var result = Enumerable.Range(0, a.Length/2)
.Select(i => a[2*i])
.ToArray();
Or use bitwise for more efficient to check even:
var result = a.Where((i, index) => (index & 1) == 0)
.ToArray();
The remainder operator is your friend.
int[] everySecond = a.Where((i, ind) => ind % 2 == 0).ToArray();
The % operator computes the remainder after dividing its first operand by its second. All numeric types have predefined remainder operators.