How to access index in IEnumerable object in C#?

dcpartners picture dcpartners · Oct 31, 2009 · Viewed 69.2k times · Source

I have an IEnumerable object. I would like to access based on index for instance:

for(i=0; i<=Model.Products; i++)
{
      ???
}

Is this possible?

Answer

Pavel Minaev picture Pavel Minaev · Nov 16, 2009

First of all, are you sure it's really IEnumerator and not IEnumerable? I strongly suspect it's actually the latter.

Furthermore, the question is not entirely clear. Do you have an index, and you want to get an object at that index? If so, and if indeed you have an IEnumerable (not IEnumerator), you can do this:

using System.Linq;
...
var product = Model.Products.ElementAt(i);

If you want to enumerate the entire collection, but also want to have an index for each element, then V.A.'s or Nestor's answers are what you want.