Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Take every 2nd object in list

I have an IEnumerable and I want to get a new IEnumerable containing every nth element.

Can this be done in Linq?

like image 658
Cristian Diaconescu Avatar asked Aug 25 '10 16:08

Cristian Diaconescu


2 Answers

Just figured it out myself...

The IEnumerable<T>.Where() method has an overload that takes the index of the current element - just what the doctor ordered.

(new []{1,2,3,4,5}).Where((elem, idx) => idx % 2 == 0);

This would return

{1, 3, 5}

Update: In order to cover both my use case and Dan Tao's suggestion, let's also specify what the first returned element should be:

var firstIdx = 1;
var takeEvery = 2;
var list =  new []{1,2,3,4,5};

var newList = list
    .Skip(firstIdx)
    .Where((elem, idx) => idx % takeEvery == 0);

...would return

{2, 4}
like image 90
Cristian Diaconescu Avatar answered Oct 06 '22 04:10

Cristian Diaconescu


To implement Cristi's suggestion:

public static IEnumerable<T> Sample<T>(this IEnumerable<T> source, int interval)
{
    // null check, out of range check go here

    return source.Where((value, index) => (index + 1) % interval == 0);
}

Usage:

var upToTen = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

var evens = upToTen.Sample(2);
var multiplesOfThree = upToTen.Sample(3);
like image 22
Dan Tao Avatar answered Oct 06 '22 06:10

Dan Tao