我怎么知道我是否正在迭代集合的最后一项?

Cam*_*tin 5 c# vb.net iteration collections foreach

我想在最后KeyValuePairDictionary迭代中做一些不同的事情.

For Each item In collection
    If ItsTheLastItem
        DoX()
    Else
        DoY()
    End If
Next 
Run Code Online (Sandbox Code Playgroud)

这可能吗?

重新编辑:我没有使用字典值,我实际上使用的是List of KeyValuePairs.我转换了它们,后来没有注意到,愚蠢的我.

Fem*_*ref 8

除非您想foreach自己实现,否则请使用计数器(C#代码):

int count = collection.Count;
int counter = 0;

foreach(var item in collection)
{
  counter++;
  if(counter == count)
    DoX();
  else
    DoY();
}
Run Code Online (Sandbox Code Playgroud)

请注意,这仅适用于非流式传输IEnumerable<T>,根据实现情况,Count也会导致集合走两次.


jas*_*son 8

我会制作你自己的扩展方法.这里的实现保证您只需走一次集合.

static class IEnumerableExtensions {
    public static void ForEachExceptTheLast<T>(
        this IEnumerable<T> source,
        Action<T> usualAction,
        Action<T> lastAction
    ) {
        var e = source.GetEnumerator();
        T penultimate;
        T last;
        if (e.MoveNext()) {
            last = e.Current;
            while(e.MoveNext()) {
                penultimate = last;
                last = e.Current;
                usualAction(penultimate);
            }
            lastAction(last);
        }
    }
}    
Run Code Online (Sandbox Code Playgroud)

用法:

Enumerable.Range(1, 5)
          .ForEachExceptTheLast(
              x => Console.WriteLine("Not last: " + x),
              x => Console.WriteLine("Last: " + x)
);
Run Code Online (Sandbox Code Playgroud)

输出:

Not last: 1
Not last: 2
Not last: 3
Not last: 4
Last: 5
Run Code Online (Sandbox Code Playgroud)


小智 7

为什么不使用:

List<string> list = new List<string>();
// add items

foreach (string text in list)
{
    if (text.Equals(list[list.Count - 1]))
    {
        // last item
    }
    else
    {
        // not last item
    }
}
Run Code Online (Sandbox Code Playgroud)


fej*_*oco 3

将集合转换为列表(如 LINQ 的 ToList())并使用 for(int i = 0)... 循环进行迭代。