user1765862
user1765862

Reputation: 14155

figuring out c# enumerators

I'm trying to understand enumerators using following example

public class Garage : IEnumerable
{
    private Car[] cars = new Car[4];
    public Garage()
    {
        cars[0] = new Car() { Id = Guid.NewGuid(), Name = "Mazda 3", CurrentSpeed = 90 };
        cars[1] = new Car() { Id = Guid.NewGuid(), Name = "Mazda 6", CurrentSpeed = 80 };
    }

    public IEnumerator GetEnumerator()
    {
        // return the array object's IEnumerator
        return cars.GetEnumerator();
    }
}

static void Main(string[] args)
    {
        IEnumerator i = cars.GetEnumerator();
        i.MoveNext();
        Car myCar = (Car)i.Current;
        Console.WriteLine("{0} is going {1} km/h", myCar.Name, myCar.CurrentSpeed);
        Console.ReadLine();

    }

How can I display on console second car without looping using foreach?

Upvotes: 3

Views: 147

Answers (5)

Felice Pollano
Felice Pollano

Reputation: 33252

You can use:

cars.Skip(1).Take(1).Single();

to have the second car ( you skip the first and then take just one);

Upvotes: 0

Matthias Meid
Matthias Meid

Reputation: 12523

You can expose an indexer to access your inner array:

public class Garage : IEnumerable
{
  public Car this[int i]
  {
    return this.cars[i];
  }
}

This is not an enumerator, since enumerators in C# are quite exclusively used to iterate over elements sequentially rather than randomly. But given you're using an array to store your cars it is fine to expose an indexer.

By the way you might want to implement the generic IEnumerable<Car> interface to make it explicit and type-safe that one can iterate over Car objects.

Upvotes: 0

PapaAtHome
PapaAtHome

Reputation: 604

The IEnumerator class is ment to be used with the foreach loop. It is not possible to access the second item without the foreach loop. (Unless you dive deep into toe internal structures of C#, not advised to do.)

Upvotes: -1

dtb
dtb

Reputation: 217313

foreach (Car myCar in cars)
{
    Console.WriteLine("{0} is going {1} km/h", myCar.Name, myCar.CurrentSpeed);
}

expands approximately to

IEnumerator i = cars.GetEnumerator();
while (i.MoveNext())
{
    Car myCar = (Car)i.Current;
    Console.WriteLine("{0} is going {1} km/h", myCar.Name, myCar.CurrentSpeed);
}

(In reality, the expansion of the foreach statement performed by the C# compiler is a bit more complicated; see The foreach statement.)

Upvotes: 8

Dennis Traub
Dennis Traub

Reputation: 51634

IEnumerator i = cars.GetEnumerator();
i.MoveNext();
Car firstCar = (Car)i.Current;
i.MoveNext();
Car secondCar = (Car)i.Current;

Upvotes: 2

Related Questions