Ullan
Ullan

Reputation: 1017

How to implement generic dictionary class?

When I try to run the following code, the foreach statement is throwing the below error at compile time

Cannot convert type 'string' to 'System.Collections.Generic.KeyValuePair>'

namespace myClass
{
public class myDictionary<T>
{
    Dictionary<string, List<T>> dictionary = new Dictionary<string, List<T>>();

    public void Add(string key, T value)
    {
        List<T> list;
        if (this.dictionary.TryGetValue(key, out list))
        {
            list.Add(value);
        }
        else
        {
            list = new List<T>();
            list.Add(value);
            this.dictionary[key] = list;
        }
    }

    public IEnumerable<string> Keys
    {
        get
        {
            return this.dictionary.Keys;
        }
    }

    public List<T> this[string key]
    {
        get
        {
            List<T> list;
            if (!this.dictionary.TryGetValue(key, out list))
            {
                list = new List<T>();
                this.dictionary[key] = list;
            }
            return list;
        }
    }

    public IEnumerator<T> GetEnumerator()
    {
        return (dictionary as IEnumerable<T>).GetEnumerator();

    }
}

class Program
{
    static void Main()
    {
        myDictionary<string> dictionary = new myDictionary<string>();

        dictionary.Add("One", "AA");
        dictionary.Add("One", "BB");
        dictionary.Add("Two", "CC");
        dictionary.Add("Two", "DD");


        foreach(KeyValuePair<string, List<string>> pair in dictionary)
        {

        }

    }
}

}

Please let me know what is wrong with my implementation. Thanks for your help.

Upvotes: 1

Views: 385

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1064114

It looks like the problem is:

public IEnumerator<T> GetEnumerator()
{
    return (dictionary as IEnumerable<T>).GetEnumerator();
}

However, you'll need to clarify what this should return, since your dictionary is one of lists. Is this meant to be all the values from all the lists in turn? If so, I guess:

public IEnumerator<T> GetEnumerator()
{
    return dictionary.Values.SelectMany(x => x).GetEnumerator();
}

If, however, you want to return the pairs, then:

public IEnumerator<KeyValuePair<string, List<T>>> GetEnumerator()
{
    return dictionary.GetEnumerator();
}

Upvotes: 2

Related Questions