F# 使用 IDictionaryEnumerator

F# working with IDictionaryEnumerator

所以我正在使用 HttpRuntime.cache,其中 returns 一个 IDictionaryEnumerator 作为它的枚举器,它似乎与 List 或 Seq 不兼容,所以我能找到使用的唯一方法它会像这样下降到邪恶的命令式代码中:

 member this.GetCountStartsWith keyPrefix =
            let enumerator = HttpRuntime.Cache.GetEnumerator()                 
            let mutable counter = 0
            while enumerator.MoveNext() do
                match enumerator.Key.ToString().StartsWith(keyPrefix) with
                | true -> counter <- counter + 1
                | false -> ()
            counter

我想我可以创建一个辅助函数来将它转储到一个列表中,但是可能有成千上万个元素,所以这在性能方面不是一个好主意。有什么方法可以以更惯用的方式处理这个东西吗?

问题是您有一个 IEnumerator,它不是通用的。但是,有两种辅助方法可以解决该问题:OfTypeCast.

在实践中,您想做如下事情:

let enumerable = HttpRuntime.Cache |> Seq.cast<DictionaryEntry>

现在 enumerable 是一个合适的泛型可枚举 :)