我正在用Fantom语言编写一个Web应用程序,并使用afMongo访问Mongo数据库实例。按照afMongo文档中的示例,我得到了需要迭代的查询结果。在一个简化的示例中,迭代看起来像这样
class MapListIterator {
Void main(){
[Str:Obj?][] listOfMaps := [,]
listOfMaps.add(
["12345":[
"id":12345,
"code":"AU",
"name":"Australia"
]])
listOfMaps.each |Str:Obj? map| {
echo(map.keys)
keys := map.keys
keys.each {
echo(it)
echo(((Str:Obj?)map[it])["code"])
echo(((Str:Obj?)map[it])["name"])
}
}
}
}
我在Fantom在线游乐场中运行了此代码,它可以正常工作,但是我想知道这是否是一种更干净的方法来遍历结果。我不喜欢上面代码中的强制转换。另外,请问有没有更好的方法来编写嵌套的it-block?
编辑:
原来我太复杂了。这是应用Steve建议后代码的外观:
Str:Country mapOfCountries := [:]
mapOfCountries.ordered = true
listOfMaps := ([Str:Str?][]) collection.findAll
listOfMaps.each {
c := it["code"]
n := it["name"]
mapOfCountries.add(c, Country { code = c ; name = n })
}
我会重新发布结果并尽早分配地图...这给出了:
listOfMappedMaps := ([Str:[Str:Obj?]][]) listOfMaps
listOfMappedMaps.each {
map := it
map.keys.each {
echo(map[it]["code"])
echo(map[it]["name"])
}
}
下一步将使用Morphia,它使您可以使用对象代替地图。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句