Possible Duplicate:
Getting odd/even part of a sequence with LINQ
How can I get every nth item from a List<T>?
I’m using HtmlAgilityPack and C# to parse some HTML.
<div id="post-8266">
<div class="ruler"> </div>
<div id="post-8266">
<div class="ruler"> </div>
<div id="post-8266">
<div class="ruler"> </div>
<div id="post-8266">
<div class="ruler"> </div>
Basically, I have these elements, each in their own object, inside of an IEnumerable.
Is there an elegant way to get each N/2 element in the collection. Meaning, skip over each div with class .ruler?
I would need to iterate through the resulting set, so either I copy each found object into a new IEnumerable or just use it inline in a foreach function.
For example:
//Copying resulting set to new IEnumerable<T>:
var odds = elements.SelectOdds();
//Using it inline for my usage:
foreach (var x in elements.SelectOdds())
{
}
Which options would be best, and how can I achieve this elegantly?
The only thing that I do not like about this solution is that it requires iterating the sequence twice if you need both the odds and the evens. If for some reason you must avoid this, you’ll have to work harder:
Then, the odds are those elements of
groupswhere theKeyisfalse, and the evens are those elements ofgroupswhere theKeyistrue: