简体   繁体   中英

Dictionary of dictionaries - IEnumerable implementation in C#

I have a "member class" with dictionary<string, string> inside and a "group class" with dictionary<string, members> . And now I want to create XML with something like this:

<group name="Group1 Name">
 <member name="Member1 Name">Member1 Value</member>
 <member name="Member2 Name">Member2 Value</member>
</group>
<group name="Group2 Name">
 <member name="Member3 Name">Member3 Value</member>
 <member name="Member4 Name">Member4 Value</member>
</group>

Previously I did it with LINQ and Select or foreach cycle. But here I have trouble with implementing of GetEnumerator method... I do not even know in which class it should be implemented? Member or group? Or probably both?

Still having errors implementing it...

public class Member : IEnumerable<Member>
{
    public Dictionary<string, string> variables = new Dictionary<string, string>();

    public Member()
    {
        //list of variables
        this.variables = new Dictionary<string, string>();
    }

    public IEnumerator<Member> GetEnumerator()
    {
        return this.variables.Keys.GetEnumerator();

    IEnumerator IEnumerable.GetEnumerator()
    {
        //forces use of the non-generic implementation on the Values collection
        return ((IEnumerable)variables.Keys).GetEnumerator();
    }


}

Thank for any advice :)

OK, thanks to Rene Vogt, I did not understand enumerators properly. His point leads me to correct way. Enumerators is a "field of keys (strings)" I can use to iterate throw dictionary and then for selecting specific member.

This was the correct implementation:

public class Member: IEnumerable<string>
    {
        public Dictionary<string, string> variables = new Dictionary<string, string>();

        public Member()
        {
            //list of variables
            this.variables = new Dictionary<string, string>();
        }


        public IEnumerator<string> GetEnumerator()
        {
            return this.variables.Keys.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            //forces use of the non-generic implementation on the Values collection
            return ((IEnumerable)variables.Keys).GetEnumerator();
        }  
    }
}

Thanks for your help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM