Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

linq

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?

like image 883
Jon Avatar asked Nov 18 '11 11:11

Jon


1 Answers

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);
like image 58
Jon Skeet Avatar answered Oct 21 '22 00:10

Jon Skeet