选择的IEnumerable&LT奇/偶元素; T&GT;? [英] Select even/odd elements in IEnumerable<T>?
问题描述
可能重复:
<一href="http://stackoverflow.com/questions/267033/getting-odd-even-part-of-a-sequence-with-linq">Getting序列与LINQ
奇/偶部分 如何从一个名单,其中获得每一个n项; T&GT ;
我用HtmlAgilityPack和C#来解析一些HTML。
&LT; DIV ID =后8266&GT;
&LT; DIV CLASS =统治者与GT; &LT; / DIV&GT;
&LT; DIV ID =后8266&GT;
&LT; DIV CLASS =统治者与GT; &LT; / DIV&GT;
&LT; DIV ID =后8266&GT;
&LT; DIV CLASS =统治者与GT; &LT; / DIV&GT;
&LT; DIV ID =后8266&GT;
&LT; DIV CLASS =统治者与GT; &LT; / DIV&GT;
基本上,我有这些元素,各自在自己的对象,里面IEnumerable的。
有一种优雅的方式来获得集合中的每个N / 2元。意,跳过每个div带班 .ruler
?
我需要遍历结果集,所以无论是我发现的每个对象复制到一个新的IEnumerable或者只是用它内嵌在foreach功能。
例如:
//复制生成的设置为新的IEnumerable&LT; T&GT;:
VAR赔率= elements.SelectOdds();
//使用它内嵌了我的用法:
的foreach(变种中的x elements.SelectOdds())
{
}
哪个选项是最好的,我怎么能做到这一点优雅?
VAR赔率= sequence.Where((项指数)=&GT;!索引%2 = 0);
VAR找齐= sequence.Where((项指数)=&GT;指数%2 == 0);
这是我不喜欢这个解决方案的唯一的事情是,它需要遍历序列两次,如果你同时需要赔率和唇上。如果由于某种原因,你必须避免这种情况,你必须更加努力地工作:
VAR组= sequence.Select((项指数)=&gt;新建{项目=项目,指数=指数})
.GroupBy(X =&GT; x.Index%2 == 0)
.ToDictionary(G =&GT; g.Key,G =&GT; G);
然后,胜算的集团
的元素,其中的键
是假
,并找齐是集团
其中键
是真
:
VAR赔率=组[虚假]
VAR找齐=组[真]
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?
var odds = sequence.Where((item, index) => index % 2 != 0);
var evens = sequence.Where((item, index) => index % 2 == 0);
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:
var groups = sequence.Select((item, index) => new { Item = item, Index = index })
.GroupBy(x => x.Index % 2 == 0)
.ToDictionary(g => g.Key, g => g);
Then, the odds are those elements of groups
where the Key
is false
, and the evens are those elements of groups
where the Key
is true
:
var odds = groups[false];
var evens = groups[true];
这篇关于选择的IEnumerable&LT奇/偶元素; T&GT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!