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

后端 未结 30 2236
刺人心
刺人心 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 07:40

    It's only going to work for a List and not any IEnumerable, but in LINQ there's this:

    IList collection = new List { 
        new Object(), 
        new Object(), 
        new Object(), 
        };
    
    foreach (Object o in collection)
    {
        Console.WriteLine(collection.IndexOf(o));
    }
    
    Console.ReadLine();
    
    
    

    @Jonathan I didn't say it was a great answer, I just said it was just showing it was possible to do what he asked :)

    @Graphain I wouldn't expect it to be fast - I'm not entirely sure how it works, it could reiterate through the entire list each time to find a matching object, which would be a helluvalot of compares.

    That said, List might keep an index of each object along with the count.

    Jonathan seems to have a better idea, if he would elaborate?

    It would be better to just keep a count of where you're up to in the foreach though, simpler, and more adaptable.

    提交回复
    热议问题