I wrote a short static method inside my class to iterate over some Hashtables I have in order of the keys (strings) but I’m getting a weird compiler error. Here’s the method in question:
public static DictionaryEntry inorderHashtable(Hashtable ht) {
string[] keys = ht.Keys.Cast<string>().ToArray<string>();
Array.Sort(keys);
foreach (string key in keys) {
yield return new DictionaryEntry(key, ht[key]);
}
}
This is later used inside the class like this:
foreach(DictionaryEntry dentry in inorderHashtable(myTable)) { /* ... */ }
Here’s the error I’m getting from VS2008: 'ns.myclass.inorderHashtable(System.Collections.Hashtable)' cannot be an iterator block because 'System.Collections.DictionaryEntry' is not an iterator interface type
What’s a way around this error? Thanks in advance.
Your method needs to have the return type
IEnumerable<DictionaryEntry>.Basically, by using
yield returninstead ofreturn, you’re not returning oneDictionaryEntry, you’re (potentially) returning many.See here and here if you’re unsure what’s going on.