Skip to main content
added 125 characters in body
Source Link
crucible
  • 3.1k
  • 2
  • 28
  • 35

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

IList<Object> collection = new List<Object> { 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.

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

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

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

IList<Object> collection = new List<Object> { 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.

Source Link
crucible
  • 3.1k
  • 2
  • 28
  • 35

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

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