c# - 有序Hashtable遍历

标签 c# visual-studio-2008 hashtable

我在我的类中写了一个简短的静态方法来迭代一些 Hashtables 我按照键(strings)的顺序但是我得到了一个奇怪的编译器错误。这是有问题的方法:

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]);
    }
}

稍后在类中这样使用:

foreach(DictionaryEntry dentry in inorderHashtable(myTable)) { /* ... */ }

这是我从 VS2008 得到的错误:'ns.myclass.inorderHashtable(System.Collections.Hashtable)' cannot be an iterator block because 'System.Collections.DictionaryEntry' is not an iterator interface type

如何解决这个错误?提前致谢。

最佳答案

您的方法需要具有返回类型 IEnumerable<DictionaryEntry> .

基本上,通过使用 yield return而不是 return ,你不会返回一个 DictionaryEntry ,您(可能)返回许多

参见 herehere如果您不确定发生了什么。

关于c# - 有序Hashtable遍历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12058564/

相关文章:

c# - 将常用函数保存在单独的 cs 文件中? (C#)

c++ - 抽象数据类型作为参数传递

c++ - 在标准的无序容器中实现了什么哈希方法?

c# - 如何将此 javascript 行转换为 c#?

c# - 获取 <compilation debug ="true"> 的 .NET Framework 设置

c# - 浏览器链接不刷新 Chrome 中的页面

c# - 将从 .bin 文件读取的数据解码到字段中

c++ - 警告 C4238 : nonstandard extension used : class rvalue used as lvalue

c# - 元组(或数组)作为 C# 中的字典键

c# - 获取 SPFieldCurrency 字段的数值