0

Quite often I found myself in a situation of needing to know what index an item is in a List while enumerating through the list. Is there any way to do this with out having to resort to using a for(var i=0...) loop?

Ideally I would like to do something like this. e.g

foreach(SomeType item in myList){
  Console.Write(item.Index);
}

jQuery has this $(this).index(); which is something like what I would like in C#

MakkyNZ
  • 2,215
  • 5
  • 33
  • 53
  • `foreach(SomeType item in myList){ Console.Write(myList.IndexOf(item).ToString());}` – Pikoh Feb 17 '16 at 14:24
  • @Pikoh well, it will work correctly only in the case of distinct items in list. Otherwise it will return index of first element having the same value as current. – Andrey Korneyev Feb 17 '16 at 14:25
  • While that will work. Ideally I don't want to need to refer directly to the parent list, as in some scenarios this might not be accessible. I want to refer to the index as a property of the object. e.g item.Index – MakkyNZ Feb 17 '16 at 14:25
  • 1
    And why would you like to avoid using simple `for` loop? – Dovydas Šopa Feb 17 '16 at 14:26
  • Try to use Select((x, index) => [code]) or plain for loop – gabba Feb 17 '16 at 14:28
  • By adding such a property you are coupling your object to a List. What possible use case do you have for that? Maybe you shouldn't be using a List? – Chris Pickford Feb 17 '16 at 14:28
  • @AndyKorneyev well,that is true for a List for example, but if the List type is a class, it will work – Pikoh Feb 17 '16 at 14:29
  • @MakkyNZ in what scenario would the parent list not be accesible? – Pikoh Feb 17 '16 at 14:31
  • @Pikoh, say for example, you pass the object into a method. Code inside that method might not have access to the parent list. e.g foreach(var item in mylist){ doSomething(item); } void doSomething(SomeType item) { Console.Write(item.index);} – MakkyNZ Feb 17 '16 at 14:36
  • You can always pass additional parameter to method like this. – Dovydas Šopa Feb 17 '16 at 14:45
  • @Dovydas changing a methods parameter signature isn't always that easy. Especially if it's implementing an interface,as a lot of other classes could be implementing the same interface. I'm looking for a solution that has none or very little impact on the rest of the code base. – MakkyNZ Feb 17 '16 at 14:50
  • @MakkyNZ there's no other way i think. Have in mind that to get the index of an item in a collection, this index must be in relation with the collection containing it. What if an item belongs to two collections? what index would you get if you did something like item.Index()? – Pikoh Feb 17 '16 at 15:37
  • @Pikoh good point. I guess that's why jQuery's $(this).index() is allowed, as an html element can't exist in two places – MakkyNZ Feb 17 '16 at 16:27

0 Answers0