even indices of an array

G

graphicsxp

Hi,

Is there a way using Linq of getting all the elements of an array for
which the index is uneven.

For instance in an array containing {3, 55, 21, 34}, I'd like to get 3
and 21.

Thanks
 
M

Michael C

graphicsxp said:
Hi,

Is there a way using Linq of getting all the elements of an array for
which the index is uneven.

For instance in an array containing {3, 55, 21, 34}, I'd like to get 3
and 21.

I think this will work, I have have VS here at the moment to test.
MyArray.Where((i, j) => (j & 1) == 0);
 
G

graphicsxp

I think this will work, I have have VS here at the moment to test.
MyArray.Where((i, j) => (j & 1) == 0);

Could you explain ? Where are i and j coming from ? This surely can't
be complete code.
 
M

miher

Hi,
If You have an array You can simply go over it with a for loop, selecting
every other element.

If You insist on LINQ:
int c = 1;
var result = YourCollection.Where(i => c++ % 2 == 1);
(I feel this is a bit "hacky", but You can try.)

Hope You find this useful.
-Zsolt
 
G

graphicsxp

Hi,
If You have an array You can simply go over it with a for loop, selecting
every other element.

If You insist on LINQ:
int c = 1;
var result = YourCollection.Where(i => c++ % 2 == 1);
(I feel this is a bit "hacky", but You can try.)

Hope You find this useful.
-Zsolt

Yep, it's working. Why do you think it's 'hacky' ? I know how to do it
with a for loop but since i'm learning LINQ, I thought it looks neater
than a for loop.

Thanks !
 
S

Stefan Hoffmann

hi,
If You insist on LINQ:
int c = 1;
var result = YourCollection.Where(i => c++ % 2 == 1);
(I feel this is a bit "hacky", but You can try.)
Maybe

var result = YourCollection.Where((p, i) => i % 2 == 0);


mfG
--> stefan <--
 
G

Göran Andersson

graphicsxp said:
Could you explain ? Where are i and j coming from ? This surely can't
be complete code.

The Where method has an overload that takes a Fun<T, int, bool> delegate.

The i parameter is the item to evaluate and the j parameter is the index
of the item.

(j & 1) gives you the least significant bit of the index. If that is
zero, you have an even number (which is what you want as the index is
zero based).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top