如何迭代F#中的哈希表?
无法编译。 我尝试过使用如何迭代F#中的哈希表?,f#,hashtable,F#,Hashtable,无法编译。 我尝试过使用Array.filter、Seq.filter、List.filter 我试着让dic.Keys迭代,但F#似乎不想让我将KeyCollection强制为IEnumerable 我已尝试将哈希表向上转换为IEnumerable 如何遍历从Environment.GetEnvironmentVariables()返回的哈希表?因为Environment.GetEnvironmentVariables()返回一个非泛型的IDictionary,它将键/值对存储在Diction
Array.filter、Seq.filter、List.filter
我试着让dic.Keys迭代,但F#似乎不想让我将KeyCollection
强制为IEnumerable
我已尝试将哈希表向上转换为IEnumerable
如何遍历从
Environment.GetEnvironmentVariables()
返回的哈希表?因为Environment.GetEnvironmentVariables()
返回一个非泛型的IDictionary
,它将键/值对存储在DictionaryEntry
中,您必须首先使用Seq.cast
:
let dic = Environment.GetEnvironmentVariables()
dic
|> Seq.filter( fun k -> k.Contains("COMNTOOLS"))
F#Seq只能在System.Collections.Generic.IEnumerable
下运行<由Environment.GetEnvironmentVariables
返回的code>System.IDictionary不是泛型的,但它实现了非泛型的System.Collections.IEnumerable
和非System.Collections.generic.IEnumerable
System.Collections.IEnumerable
不包含类型信息,并允许枚举装箱类型的集合,即System.Object的实例。
无论如何,System.IDictionary
可以被枚举为System.Collections.DictionaryEntry
对象的集合,因此您可以简单地对其调用Seq.cast
。它将允许您访问键
和值
属性,但仍然作为对象装箱,因此您也应该取消装箱
let dic = Environment.GetEnvironmentVariables()
seq {
for entry in Seq.cast<DictionaryEntry> dic ->
(string entry.Key), (string entry.Value)
}
|> Seq.filter(fun (k, _) -> k.Contains("COMNTOOLS"))
let dic=System.Environment.GetEnvironmentVariables()
dic
|>序号
|>序列过滤器(fun k->(k.Key:?>字符串)。包含(“COMNTOOLS”))
或者,您可以使用以下功能
let dic = System.Environment.GetEnvironmentVariables()
dic
|> Seq.cast<System.Collections.DictionaryEntry>
|> Seq.filter( fun k -> (k.Key :?> string).Contains("COMNTOOLS"))
let-asStringPairSeq(d:System.Collections.IDictionary):seq=
序号d
|>序列图(有趣的千伏->千伏键:?>串,千伏值:?>串)
System.Environment.GetEnvironmentVariables()
|>asStringPairSeq
|>顺序过滤器(乐趣(k,v)->k.Contains(“COMNTOOLS”))
您应该指定实际错误,尽管我怀疑它与k.Contains有关k
是一个KeyValuePari,因此在添加更多详细信息和删除实际错误之前,当我键入它时,Contains
不存在,它是:无法执行文本选择:类型IDictionary
与类型seqFirst代码块不兼容。未编译:类型DictionaryEntry
没有任何正确的子类型,不能用作类型测试或运行时强制的源。第二个块未编译,因为似乎没有System.Collections.Dictionary
,并给出了附加错误:“Microsoft.FSharp.Collections.seq”类型需要1个类型参数,但给出的2个类型参数可能应该是string*string
。
let dic = System.Environment.GetEnvironmentVariables()
dic
|> Seq.cast<System.Collections.DictionaryEntry>
|> Seq.filter( fun k -> (k.Key :?> string).Contains("COMNTOOLS"))
let asStringPairSeq (d : System.Collections.IDictionary) : seq<string * string> =
Seq.cast<System.Collections.DictionaryEntry> d
|> Seq.map (fun kv -> kv.Key :?> string, kv.Value :?> string)
System.Environment.GetEnvironmentVariables()
|> asStringPairSeq
|> Seq.filter (fun (k,v) -> k.Contains("COMNTOOLS"))