【问题标题】:Get index of Enumerator.Current in C# [duplicate]在 C# 中获取 Enumerator.Current 的索引 [重复]
【发布时间】:2023-04-07 02:14:01
【问题描述】:

可能重复:
(C#) Get index of current foreach iteration

早上好,

有什么方法可以在不使用辅助变量的情况下获取Enumerator 的当前元素(在这种情况下是字符串中的字符)的索引?我知道如果我使用whilefor cicle,这可能会更容易,但是使用枚举器循环遍历字符串更优雅......这种情况的唯一缺点是我真的需要获取每个字符的当前索引。

非常感谢。

【问题讨论】:

  • 创建一个包装类?

标签: c#


【解决方案1】:

不,IEnumerator 接口不支持此类功能。

如果你需要这个,你要么必须自己实现,要么使用不同的接口,比如IList

【讨论】:

    【解决方案2】:

    不,没有。如果你真的需要索引,最优雅的方法是使用 for 循环。使用迭代器模式实际上是less优雅(而且更慢)。

    【讨论】:

      【解决方案3】:

      Linq 的Select 有合适的重载。但是你可以使用这样的东西:

      foreach(var x in "ABC".WithIndex())
      {
          Console.Out.WriteLine(x.Value + " " + x.Index);
      }
      

      使用这些助手:

      public struct ValueIndexPair<T>
      {
          private readonly T mValue;
          private readonly int mIndex;
      
          public T Value { get { return mValue; } }
          public int Index { get { return mIndex; } }
      
          public override string ToString()
          {
              return "(" + Value + "," + Index + ")";
          }
      
          public ValueIndexPair(T value, int index)
          {
              mValue = value;
              mIndex = index;
          }
      }
      
      public static IEnumerable<ValueIndexPair<T>> WithIndex<T>(this IEnumerable<T> sequence)
      {
          int i = 0;
          foreach(T value in sequence)
          {
              yield return new ValueIndexPair<T>(value, i);
              i++;
          }
      }
      

      【讨论】:

      • 为了“更优雅”并避免简单的 for 循环而产生了很多噪音。
      • 大部分噪音最终会进入图书馆。但我也不会使用它。我只是使用 Linq 或创建一个额外的变量。
      猜你喜欢
      • 2011-09-24
      • 2013-12-10
      • 2021-07-19
      • 2013-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-10
      • 1970-01-01
      相关资源
      最近更新 更多