Using Skip and Take to Select Alternative Elements in an Array

I have a string array with the following elements:

string s = "M,k,m,S,3,a,5,E,2,Q,7,E,8,J,4,Y,1,m,8,N,3,P,5,H";
 var items = s.split(',');
 var topThree = items.Take(3);
 var alternating1 = items.Skip(3).Take(1).Skip(1).Take(1).Skip(1).Take(1).Skip(1).Take(1);

There is nothing in the variable alternating1, and I think I understand why. After Skipping, then Take, it returns 1 element in it, then try to skip (1) and Take (1), but there is nothing there.

Is there any way to make this striped pattern?

+5
source share
1 answer

The easiest approach is to use an overload Wherethat takes an index:

var alternating = input.Where((value, index) => (index & 1) == 0);

Or use % 2instead, equivalently:

var alternating = input.Where((value, index) => (index % 2) == 0);
+11
source

All Articles