代码之家  ›  专栏  ›  技术社区  ›  Ken

带索引的foreach[重复]

  •  136
  • Ken  · 技术社区  · 17 年前

    enumerate() 还有鲁比的 each_with_index ?

    10 回复  |  直到 10 年前
        1
  •  268
  •   AustinWBryan ravenspoint    7 年前

    public static void Each<T>(this IEnumerable<T> ie, Action<T, int> action)
    {
        var i = 0;
        foreach (var e in ie) action(e, i++);
    }
    

    像这样使用:

    var strings = new List<string>();
    strings.Each((str, n) =>
    {
        // hooray
    });
    

    break -喜欢的行为:

    public static bool Each<T>(this IEnumerable<T> ie, Func<T, int, bool> action)
    {
        int i = 0;
        foreach (T e in ie) if (!action(e, i++)) return false;
        return true;
    }
    
    var strings = new List<string>() { "a", "b", "c" };
    
    bool iteratedAll = strings.Each ((str, n)) =>
    {
        if (str == "b") return false;
        return true;
    });
    
        2
  •  229
  •   vzwick pasujemito    6 年前

    foreach (var it in someCollection.Select((x, i) => new { Value = x, Index = i }) )
    {
       if (it.Index > SomeNumber) //      
    }
    

    这将为集合中的每个条目创建一个匿名类型值。它将有两个属性

    • Value :具有集合中的原始值
    • Index :集合中的索引
        3
  •  67
  •   David Morton    11 年前

    C#foreach没有内置索引。您需要在foreach循环外添加一个整数,并每次递增。

    int i = -1;
    foreach (Widget w in widgets)
    {
       i++;
       // do something
    }
    

    或者,可以使用标准for循环,如下所示:

    for (int i = 0; i < widgets.Length; i++)
    {
       w = widgets[i];
       // do something
    }
    
        4
  •  16
  •   obsoleter Daniel K    11 年前

    public struct EnumeratedInstance<T>
    {
        public long cnt;
        public T item;
    }
    
    public static IEnumerable<EnumeratedInstance<T>> Enumerate<T>(this IEnumerable<T> collection)
    {
        long counter = 0;
        foreach (var item in collection)
        {
            yield return new EnumeratedInstance<T>
            {
                cnt = counter,
                item = item
            };
            counter++;
        }
    }
    

    举个例子:

    foreach (var ii in new string[] { "a", "b", "c" }.Enumerate())
    {
        Console.WriteLine(ii.item + ii.cnt);
    }
    

    一件好事是,如果您习惯了Python语法,您仍然可以使用它:

    foreach (var ii in Enumerate(new string[] { "a", "b", "c" }))
    
        5
  •  15
  •   Jon Skeet    7 年前

    除了已经给出的LINQ答案,我还有一个 "SmartEnumerable" 类,它允许您获取索引和“第一个/最后一个”属性。它的语法有点难看,但你可能会发现它很有用。

    我们可以在非泛型中使用静态方法改进类型推理,隐式类型也会有所帮助。

        6
  •  6
  •   Chris Ammerman    17 年前

    ordinal ").

    这些函数将为每个项返回一个包含索引和项本身的Pair对象。

    public static IEnumerable<Pair<Int32, X>> Ordinate<X>(this IEnumerable<X> lhs)
    {
        return lhs.Ordinate(0);
    }
    
    public static IEnumerable<Pair<Int32, X>> Ordinate<X>(this IEnumerable<X> lhs, Int32 initial)
    {
        Int32 index = initial - 1;
    
        return lhs.Select(x => new Pair<Int32, X>(++index, x));
    }
    
        7
  •  3
  •   Peter Mortensen Pieter Jan Bonestroo    11 年前

    不,没有。

    正如其他人所展示的,有很多方法可以模拟Ruby的行为。但是有一个实现 IEnumerable 不公开索引的。

        8
  •  1
  •   vonWippersnap    14 年前

    这是你的收藏

    var values = new[] {6, 2, 8, 45, 9, 3, 0};
    

    为此集合创建一系列索引

    var indexes = Enumerable.Range(0, values.Length).ToList();
    

    使用范围进行索引迭代

    indexes.ForEach(i => values[i] += i);
    indexes.ForEach(i => Console.Write("[{0}] = {1}", i, values[i]));
    
        9
  •  1
  •   Peter Mortensen Pieter Jan Bonestroo    11 年前

    public class DepthAware<T> : IEnumerable<T>
    {
        private readonly IEnumerable<T> source;
    
        public DepthAware(IEnumerable<T> source)
        {
            this.source = source;
            this.Depth = 0;
        }
    
        public int Depth { get; private set; }
    
        private IEnumerable<T> GetItems()
        {
            foreach (var item in source)
            {
                yield return item;
                ++this.Depth;
            }
        }
    
        public IEnumerator<T> GetEnumerator()
        {
            return GetItems().GetEnumerator();
        }
    
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
    
    // Generic type leverage and extension invoking
    public static class DepthAware
    {
        public static DepthAware<T> AsDepthAware<T>(this IEnumerable<T> source)
        {
            return new DepthAware<T>(source);
        }
    
        public static DepthAware<T> New<T>(IEnumerable<T> source)
        {
            return new DepthAware<T>(source);
        }
    }
    

    用法:

    var chars = new[] {'a', 'b', 'c', 'd', 'e', 'f', 'g'}.AsDepthAware();
    
    foreach (var item in chars)
    {
        Console.WriteLine("Char: {0}, depth: {1}", item, chars.Depth);
    }
    
        10
  •  0
  •   VBNight    17 年前

    这取决于你正在使用的类。

    出于枚举的目的,字典中的每个项都被视为KeyValuePair<(共<(TKey,TValue>)>)表示值及其键的结构。返回项目的顺序未定义。

    foreach(myDictionary中的KeyValuePair kvp){…}