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?
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.
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.
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!
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.
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++; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With