12

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 }
Asif Mushtaq
  • 13,010
  • 3
  • 33
  • 42
l33t
  • 18,692
  • 16
  • 103
  • 180

3 Answers3

28
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

Loofer
  • 6,841
  • 9
  • 61
  • 102
Asif Mushtaq
  • 13,010
  • 3
  • 33
  • 42
10

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();
cuongle
  • 74,024
  • 28
  • 151
  • 206
8

The remainder operator is your friend.

int[] everySecond = a.Where((i, ind) => ind % 2 == 0).ToArray();

% Operator (C# Reference)

The % operator computes the remainder after dividing its first operand by its second. All numeric types have predefined remainder operators.

E.Lippert: What's the difference? Remainder vs Modulus

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939