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:
% Operator
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();
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With