Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select every second element from array using lambda [duplicate]

Tags:

c#

lambda

linq

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 }
like image 980
l33t Avatar asked Oct 26 '12 07:10

l33t


2 Answers

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

like image 61
Asif Mushtaq Avatar answered Oct 24 '22 16:10

Asif Mushtaq


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();
like image 20
cuongle Avatar answered Oct 24 '22 16:10

cuongle