问题描述
我有一个 IEnumerable<T>
.我要为集合的每个项目(最后一个项目除外)做一件事情,我想对它做其他事情.我该如何整齐地编写代码?在伪代码中
I have an IEnumerable<T>
. I want to do one thing for each item of the collection, except the last item, to which I want to do something else. How can I code this neatly? In Pseudocode
foreach (var item in collection)
{
if ( final )
{
g(item)
}
else
{
f(item)
}
}
因此,如果我的IEnumerable是Enumerable.Range(1,4)
,我会执行f(1)f(2)f(3)g(4).注意如果我的IEnumerable恰好是长度1,我想要g(1).
So if my IEnumerable were Enumerable.Range(1,4)
I'd do f(1) f(2) f(3) g(4). NB. If my IEnumerable happens to be length 1, I want g(1).
我的IEnumerable恰好有点cr脚,使Count()
与遍历整个事情一样昂贵.
My IEnumerable happens to be kind of crappy, making Count()
as expensive as looping over the whole thing.
推荐答案
由于您提到IEnumerable[<T>]
(不是IList[<T>]
等),我们不能依赖计数等:因此,我很想展开:
Since you mention IEnumerable[<T>]
(not IList[<T>]
etc), we can't rely on counts etc: so I would be tempted to unroll the foreach
:
using(var iter = source.GetEnumerator()) {
if(iter.MoveNext()) {
T last = iter.Current;
while(iter.MoveNext()) {
// here, "last" is a non-final value; do something with "last"
last = iter.Current;
}
// here, "last" is the FINAL one; do something else with "last"
}
}
请注意,以上内容在技术上仅对IEnuemerable<T>
有效;对于非泛型,您需要:
Note the above is technically only valid for IEnuemerable<T>
; for non-generic, you'd need:
var iter = source.GetEnumerator();
using(iter as IDisposable) {
if(iter.MoveNext()) {
SomeType last = (SomeType) iter.Current;
while(iter.MoveNext()) {
// here, "last" is a non-final value; do something with "last"
last = (SomeType) iter.Current;
}
// here, "last" is the FINAL one; do something else with "last"
}
}
这篇关于IEnumerable foreach,对最后一个元素做一些不同的事情的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!