Jon
Jon

Reputation: 40062

Using Skip and Take to pick up alternate items in an array

I have a string array with the following items:

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);

The alternating1 variable has nothing in it and I think I understand why. After the Skip then Take it returns 1 item in it so it then tries to Skip(1) and Take(1) but there is nothing there.

Is there a way I can do this alternating pattern?

Upvotes: 5

Views: 1015

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503220

The simplest approach would be to use the Where overload which takes an index:

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

Or to use % 2 instead, equivalently:

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

Upvotes: 12

Related Questions