简体   繁体   中英

In order Hashtable traversal

I wrote a short static method inside my class to iterate over some Hashtable s I have in order of the keys ( string s) 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 return instead of return , you're not returning one DictionaryEntry , you're (potentially) returning many .

See here and here if you're unsure what's going on.

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