IEnumerable foreach, do something different for the last element

后端 未结 5 2302
庸人自扰
庸人自扰 2021-02-20 06:23

I have an IEnumerable. 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? I

5条回答
  •  -上瘾入骨i
    2021-02-20 06:43

    Since you mention IEnumerable[] (not IList[] 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"
        }
    }
    

    Note the above is technically only valid for IEnuemerable; 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"
        }
    }
    

提交回复
热议问题