TCM
TCM

Reputation: 16910

How can you select all even numbered position items from IEnumerable?

How can you select all even numbered position from IEnumerable?

Say I have IEnumerable<int> as

3,5,7,9,10

Output should be 5, 9.

Which lambda do I need to write?

Upvotes: 2

Views: 362

Answers (3)

Rich Tebb
Rich Tebb

Reputation: 7126

Here's what you need:

int[] values = new[] {3,5,7,9,10};
var everyOtherValue = values.Where((v, idx) => idx % 2 != 0);

Upvotes: 1

Tim Croydon
Tim Croydon

Reputation: 1896

Something like this:

var nums = new int[] { 3, 5, 7, 9, 10 };

var results = nums.Where((n, i) => i % 2 != 0);

Upvotes: 2

Mark Byers
Mark Byers

Reputation: 838974

Use the overload of Enumerable.Where with the predicate function that also takes the index:

IEnumerable<int> result = ints.Where((x, i) => i % 2 == 1);

Upvotes: 13

Related Questions