How do you get the index of the current iteration of a foreach loop?

后端 未结 30 2058
刺人心
刺人心 2020-11-22 07:05

Is there some rare language construct I haven\'t encountered (like the few I\'ve learned recently, some on Stack Overflow) in C# to get a value representing the current iter

30条回答
  •  野性不改
    2020-11-22 07:28

    You could wrap the original enumerator with another that does contain the index information.

    foreach (var item in ForEachHelper.WithIndex(collection))
    {
        Console.Write("Index=" + item.Index);
        Console.Write(";Value= " + item.Value);
        Console.Write(";IsLast=" + item.IsLast);
        Console.WriteLine();
    }
    

    Here is the code for the ForEachHelper class.

    public static class ForEachHelper
    {
        public sealed class Item
        {
            public int Index { get; set; }
            public T Value { get; set; }
            public bool IsLast { get; set; }
        }
    
        public static IEnumerable> WithIndex(IEnumerable enumerable)
        {
            Item item = null;
            foreach (T value in enumerable)
            {
                Item next = new Item();
                next.Index = 0;
                next.Value = value;
                next.IsLast = false;
                if (item != null)
                {
                    next.Index = item.Index + 1;
                    yield return item;
                }
                item = next;
            }
            if (item != null)
            {
                item.IsLast = true;
                yield return item;
            }            
        }
    }
    

提交回复
热议问题