Howto implement multiple enumerators to support foreach functionality

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Benjamin

    Howto implement multiple enumerators to support foreach functionality

    I am attempting to create multiple itterators for a custom class that I have created. Basically I have a class that I am populating using XML de-serialization. I want to be able to loop through the class using a foreach loop. I realize that in order to do this I need to create my own GetEnumerator that implements the movenext and current methods.

    The problem that I have is that I have been able to implement this for only one of the classes that is encapsulated in the parent class. When I attempt to create an additional enumerator I receive Error 1 Error 1 Type 'MyCollection.m yclass' already defines a member called 'GetEnumerator' with the same parameter types Collection.cs 117 29 xml.

    The following pseudo code demonstrates what I am trying to achieve. Using the example bellow I am only able to implement a single enumerator at this stage, I would like to be able to implement an enumerator for each of the classes wrapped by earth (ie one for Country and one for City)

    Any suggestions or pointers on how to do this? I have looked at http://msdn2.microsoft.com/en-us/library/9yb8xew9.aspx and managed to implement a single enumerator based on this.

    Many thanks

    Benjamin



    /**
    * Class structure that we will be serializing
    */
    class Earth
    {
    [XmlElement]
    public Country[] country;
    [XmlElement]
    public City[] city;
    }

    class Country
    {
    [XmlAttribute]
    string name;
    }

    class City
    {
    [XmlAttribute]
    string name;
    }

    /**
    * Decerialize the xml data
    */
    Earth myEarth = new Earth();
    StreamReader xmlInFile = new StreamReader("s ome.xml");
    using (xmlInFile)
    {
    XmlSerializer mySerializer = new XmlSerializer(t ypeof(Earth));
    myEarth = (Earth)mySerial izer.Deserializ e(xmlInFile);
    }

    /**
    * And display the data
    */
    foreach (Country myCountry in Earth)
    {
    Console.WriteLi ne("Country: {0}", myCountry.name) ;
    foreach (City myCity in Country)
    {
    Console.WriteLi ne("City: {0}", myCity.name);
    }
    }


Working...