2

请考虑以下 C# 块:

int resultIndex = 0;

Result firstResult = results.First();
DoAVeryImportOperationWithFirstResult(firstResult);

Console.WriteLine(String.Format("This is the {0} result.", resultIndex++));
yield return firstResult;

foreach(Result result in results)
{
   Console.WriteLine(String.Format("This is the {0} result.", resultIndex++));
   yield return result;
}

如果您熟悉 Linq 和迭代器,您会注意到在foreach块的第一次迭代中,将返回 results 的第一个结果而不是第二个结果。

所以,基本上这是我的问题:我无法从迭代器方法中获取第一个值,然后在不重新启动此方法的情况下在其他地方使用它。

有人知道一些解决方法吗?

4

5 回答 5

7

Others have shown the approach using a foreach loop and conditional execution. That's actually a neat approach - but here's another option in case the foreach loop is inappropriate for whatever reason.

using (var iterator = results.GetEnumerator())
{
    if (!iterator.MoveNext())
    {
        // Throw some appropriate exception here.
    }

    Result firstResult = iterator.Current;
    DoAVeryImportOperationWithFirstResult(firstResult);

    Console.WriteLine(String.Format("This is the {0} result.", resultIndex++));
    yield return firstResult;

    while (iterator.MoveNext())
    {
        Result result = iterator.Current;
        Console.WriteLine(String.Format("This is the {0} result.", resultIndex++));
        yield return result;
    }
}
于 2013-02-19T22:07:48.677 回答
3

只需明确地这样做:

bool first = true;
foreach(var item in results) {
    if(first) {
        first = false;
        // whatever
    } else {
        // whatever else
    }
}

或更复杂:

using(var iter = results.GetEnumerator()) {
    if(iter.MoveNext()) {
        // do first things with iter.Current

        while(iter.MoveNext()) {
            // do non-first things with iter.Current
        }
    }
}
于 2013-02-19T22:06:12.130 回答
3

您需要手动迭代:

var enumerator = results.GetEnumerator();
enumerator.MoveNext();
yield return enumerator.Current; //first
while(enumerator.MoveNext())
 yield return enumerator.Current; //2nd, ...

省略所有错误检查...也不要忘记处理。

于 2013-02-19T22:06:13.830 回答
3
bool isFirst = true;
foreach(Result result in results)
{
   if(isFirst)
   {
      DoAVeryImportOperationWithFirstResult(firstResult);
      isFirst = false;
   }

   Console.WriteLine(String.Format("This is the {0} result.", resultIndex++));
   yield return result;
}
于 2013-02-19T22:07:10.330 回答
2

您需要使用跳过

foreach(Result result in results.Skip(1))
{
   Console.WriteLine(String.Format("This is the {0} result.", resultIndex++));
   yield return result;
}

或手动迭代结果。

如果您考虑如何实现迭代器,您所看到的确实是预期的行为!

于 2013-02-19T22:06:17.167 回答