tags:

views:

1108

answers:

4

Hi there

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

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

Is this possible?

+3  A: 
var myProducts = Models.Products.ToList();
for(i=0; i< myProducts.Count ; i++)
{
      //myProducts[i];
}
Ngu Soon Hui
shouldn't it be i < myProducts.Count :)
Greco
and also beaware that .ToList() is creating a new list in memory. Is that worth it (all that waste just to have an index?)
Nestor
That's pretty nasty. So if there are 10,000 products, and he needs the 5th, you tell him to load all 10k into memory first, just to discard the 9,554 he won't need?
Pavel Minaev
@Nestor: That would really depend on the situation. I don't see a reason for needing an index anyway (a counter would do), so who knows.
Ed Swangren
+12  A: 

There is no index in IEnumerator. Use

foreach(var item in Model.Products)
{
   ...item...
}

you can make your own index if you want:

int i=0;
foreach(var item in Model.Products)
{
    ... item...
    i++;
}
Nestor
+1  A: 
foreach(var indexedProduct in Model.Products.Select((p, i)=> new {Product = p, Index = i})
{
   ...
   ...indexedProduct.Product...
   ...indexProduct.Index ...//this is what you need.
   ...
}
V.A.
+6  A: 

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.

Pavel Minaev