【问题标题】:How to use the iterating variable after a foreach如何在foreach之后使用迭代变量
【发布时间】:2021-12-22 16:31:45
【问题描述】:
foreach (var (counter, _, _) in Count())
{
    ... // do stuff with counter
}
return counter;

counter 在foreach 之后超出范围,因此上述方法不起作用。

如何在循环之后使用迭代变量之一,而不是

int latestCounter;
foreach (var (counter, _, _) in Count())
{
    ... // do stuff with counter
    latestCounter = counter;
}
return latestCounter;

【问题讨论】:

  • 你的解决方案有什么问题?
  • 由于Count() 在foreach 循环中工作,它必须返回IEnumerable<> 类型。为什么不直接使用 System.Linq 中的 Last() 而使用 return Count().Select(_ => _.Item1).Last();?
  • 这是一个XY问题的例子,你想达到什么目的?
  • @OmarAbdelBari 迭代两次
  • 除非有你没有显示的代码然后没有,这完全消除了foreach循环的需要。

标签: c# foreach scope valuetuple deconstructor


【解决方案1】:

调用 MoveNext() 直到最后

    List<int> Count = new List<int>();
    IEnumerator<int> e = Count.GetEnumerator();
    if (e.MoveNext())
    {
        while (true)
        {
            var current = e.Current;
            bool anyNext = e.MoveNext();
            if (!anyNext)
            {
                // here in last
                break;
            }
        }
    }
        

【讨论】:

  • 这几乎是问题开始的地方:(有效地)foreach 循环,在每次迭代时将迭代变量分配给包含范围内定义的变量。
  • 关于编辑,Current 在调用MoveNext() 之前是未定义的。此外,如果Count 为空,那么您将永远无法将break 排除在while(true) 之外。我认为您必须像以前的版本一样从if (e.MoveNext()) 开始以解决这两个问题。
  • 好的,我编辑了我的答案@LanceU.Matthews
猜你喜欢
  • 2012-08-02
  • 1970-01-01
  • 2013-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多