c# - IEnumerable foreach,对最后一个元素做一些不同的事情

标签 c# .net ienumerable control-flow

我有一个 IEnumerable<T> .我想为集合中的每个项目做一件事,除了最后一个项目,我想对它做其他事情。我怎样才能整齐地编码呢?在伪代码中

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)。

我的 IEnumerable 碰巧有点糟糕,使 Count()和遍历整个事情一样昂贵。

最佳答案

自从你提到 IEnumerable[<T>] (不是 IList[<T>] 等),我们不能依赖计数等:所以我很想展开 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> 有效;对于非通用,您需要:

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"
    }
}

关于c# - IEnumerable foreach,对最后一个元素做一些不同的事情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10735727/

相关文章:

c# - Dispose 与 Iterator block

c# - 错误 : IEnumerable could Not be defined in non-generic static class

c# - 从 Windows 10 UWP 中的路径启动文件

c# - 如何在单元测试中验证 Flurl Http 中的请求正文内容?

c# - 异步调用 webservice 方法

c# - Application insights 读取响应正文

c# - 使用枚举的 C# 中的笛卡尔积

C# 将位图转换为 FFmediaToolkits ImageData

c# - 图片框 C# 中的圆角边缘

c# - 如何使用 LINQ to Entities 更新现有对象的属性?