2017-07-03 33 views
1

當我嘗試運行下面的代碼中,的foreach聲明是在編譯時如何實現通用字典類?

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) 
     { 

     } 

    } 
} 

}

請讓我知道什麼是錯我的執行拋出下面的錯誤。謝謝你的幫助。

+0

你的foreach語句預計'MyDictionary '來實現IEnumerable >'。所以,如果你想要它的工作,你需要實現這一點,可能通過委託給私人'字典<字符串,列表>' – Joe

回答

2

它看起來像問題是:

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

但是,你需要澄清一下這個應該回報,因爲你的字典是列表中的一個。這是否意味着依次是所有列表中的所有值?如果是這樣,我想:

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

但是,如果你想要回對,則:

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

你有多快?這樣的速度! – Alisson

+0

我需要循環槽字典並獲取所有列表值進行處理..現在我看到了錯誤:System.Collections.Generic.Dictionary > .ValueCollection.Enumerator'到'System.Collections.Generic.IEnumerator ' – Ullan

+0

@烏蘭你看到了編輯? –