Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access index in IEnumerable object in C#?

Tags:

c#

ienumerable

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?

like image 373
dcpartners Avatar asked Oct 31 '09 12:10

dcpartners


People also ask

How do I access items in IEnumerable?

var item = eLevelData. ElementAt(index); If your collection is typed as IEnumerable instead of IEnumerable<T> you'll need to use the Cast extension method before you can call ElementAt e.g.

What is IEnumerable <>?

IEnumerable is an interface defining a single method GetEnumerator() that returns an IEnumerator interface. It is the base interface for all non-generic collections that can be enumerated. This works for read-only access to a collection that implements that IEnumerable can be used with a foreach statement.

Can you use Linq on IEnumerable?

All LINQ methods are extension methods to the IEnumerable<T> interface. That means that you can call any LINQ method on any object that implements IEnumerable<T> . You can even create your own classes that implement IEnumerable<T> , and those classes will instantly "inherit" all LINQ functionality!


2 Answers

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.

like image 77
Pavel Minaev Avatar answered Sep 21 '22 19:09

Pavel Minaev


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++; } 
like image 34
Nestor Avatar answered Sep 20 '22 19:09

Nestor