提前終止

你可以通過呼叫 yield break 來傳遞一個或多個可以在函式中定義終止條件的值或元素來擴充套件現有 yield 方法的功能,以阻止內迴圈執行。

public static IEnumerable<int> CountUntilAny(int start, HashSet<int> earlyTerminationSet)
{
    int curr = start;

    while (true)
    {
        if (earlyTerminationSet.Contains(curr))
        {
            // we've hit one of the ending values
            yield break;
        }

        yield return curr;

        if (curr == Int32.MaxValue)
        {
            // don't overflow if we get all the way to the end; just stop
            yield break;
        }

        curr++;
    }
}

上述方法將從給定的 start 位置迭代,直到遇到 earlyTerminationSet 中的一個值。

// Iterate from a starting point until you encounter any elements defined as 
// terminating elements
var terminatingElements = new HashSet<int>{ 7, 9, 11 };
// This will iterate from 1 until one of the terminating elements is encountered (7)
foreach(var x in CountUntilAny(1,terminatingElements))
{
    // This will write out the results from 1 until 7 (which will trigger terminating)
    Console.WriteLine(x);
}

輸出:

1
2
3
4
5
6

.NET 小提琴現場演示