even indices of an array

  • Thread starter Thread starter graphicsxp
  • Start date Start date
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
 
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);
 
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.
 
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
 
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 !
 
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 <--
 
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).
 
Back
Top