严格来说,我想说,如果您想完全按照您所说的去做,那么是的,您需要调用 GetEnumerator 并使用 while 循环自己控制枚举器。
在不太了解您的业务需求的情况下,您也许可以利用迭代器函数,例如:
public static IEnumerable<decimal> IgnoreSmallValues(List<decimal> list)
{
decimal runningTotal = 0M;
foreach (decimal value in list)
{
// if the value is less than 1% of the running total, then ignore it
if (runningTotal == 0M || value >= 0.01M * runningTotal)
{
runningTotal += value;
yield return value;
}
}
}
然后你可以这样做:
List<decimal> payments = new List<decimal>() {
123.45M,
234.56M,
.01M,
345.67M,
1.23M,
456.78M
};
foreach (decimal largePayment in IgnoreSmallValues(payments))
{
// handle the large payments so that I can divert all the small payments to my own bank account. Mwahaha!
}
更新:
好的,这是我所谓的“钓鱼钩”解决方案的后续内容。现在,让我添加一个免责声明,我真的想不出这样做的充分理由,但您的情况可能会有所不同。
这个想法是您只需创建一个传递给迭代器函数的“钓鱼钩”对象(引用类型)。迭代器函数操作您的钓鱼钩对象,并且由于您在外部代码中仍然有对它的引用,因此您可以看到正在发生的事情:
public class FishingHook
{
public int Index { get; set; }
public decimal RunningTotal { get; set; }
public Func<decimal, bool> Criteria { get; set; }
}
public static IEnumerable<decimal> FishingHookIteration(IEnumerable<decimal> list, FishingHook hook)
{
hook.Index = 0;
hook.RunningTotal = 0;
foreach(decimal value in list)
{
// the hook object may define a Criteria delegate that
// determines whether to skip the current value
if (hook.Criteria == null || hook.Criteria(value))
{
hook.RunningTotal += value;
yield return value;
hook.Index++;
}
}
}
你会像这样使用它:
List<decimal> payments = new List<decimal>() {
123.45M,
.01M,
345.67M,
234.56M,
1.23M,
456.78M
};
FishingHook hook = new FishingHook();
decimal min = 0;
hook.Criteria = x => x > min; // exclude any values that are less than/equal to the defined minimum
foreach (decimal value in FishingHookIteration(payments, hook))
{
// update the minimum
if (value > min) min = value;
Console.WriteLine("Index: {0}, Value: {1}, Running Total: {2}", hook.Index, value, hook.RunningTotal);
}
// Resultint output is:
//Index: 0, Value: 123.45, Running Total: 123.45
//Index: 1, Value: 345.67, Running Total: 469.12
//Index: 2, Value: 456.78, Running Total: 925.90
// we've skipped the values .01, 234.56, and 1.23
从本质上讲,FishingHook 对象让您可以控制迭代器的执行方式。我从这个问题中得到的印象是,您需要某种方式来访问迭代器的内部工作,以便您可以在迭代过程中操纵它的迭代方式,但如果不是这种情况,那么这个解决方案可能对你需要的东西太过分了。