2017-07-03 9 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をを実装する予定> '。だから、もしそれを動作させたいのであれば、これを実装する必要があります。おそらくプライベートな 'Dictionary >' – Joe

答えて

2

問題があるように見えます:

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

しかし、あなたはあなたの辞書は、リストの1であるので、この、返すべきかを明確にする必要があります。これはすべてのリストからすべての値になることを意味していますか?もしそうなら、私は推測:

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 ' to 'System.Collections.Generic.IEnumerator ' – Ullan

+0

@Ullanあなたは編集を見ましたか? –

関連する問題