Dictionary F#错误,地图包括字典
我做了一张地图,里面有几本字典。每次收到数据时,我都会在地图中找到相应的字典,然后在此字典中添加新信息。 但问题是每次我尝试添加信息时,它不会只在相应的字典中添加信息,而是会将其添加到地图中的所有字典中。 拜托,我快疯了Dictionary F#错误,地图包括字典,dictionary,map,f#,add,Dictionary,Map,F#,Add,我做了一张地图,里面有几本字典。每次收到数据时,我都会在地图中找到相应的字典,然后在此字典中添加新信息。 但问题是每次我尝试添加信息时,它不会只在相应的字典中添加信息,而是会将其添加到地图中的所有字典中。 拜托,我快疯了 while datareceive do let refdictionary = ref totalmap.[index] //totalmap has a lot of Dictionary, which is indexed by "index" le
while datareceive do
let refdictionary = ref totalmap.[index] //totalmap has a lot of Dictionary, which is indexed by "index"
let dictionnarydata = totalmap.[index]
if dictionnarydata.ContainsKey(key1) then
........
else
refdic.Value.Add(key1,num) //if the corresponding dictionary does not have such information, then add it in it
()
如评论中所述,如果您正在学习函数式编程,那么最好的方法是使用不可变的数据结构——在这里,您可以使用一个映射,将索引映射到嵌套映射(其中包含您需要的键值信息) 尝试使用以下示例:
// Add new item (key, num pair) to the map at the specified index
// Since totalMap is immutable, this returns a new map!
let addData index (key:int) (num:int) (totalmap:Map<_, Map<_, _>>) =
// We are assuming that the value for index is defined
let atIndex = totalmap.[index]
let newAtIndex =
// Ignore information if it is already there, otherwise add
if atIndex.ContainsKey key then atIndex
else atIndex.Add(key, num)
// Using the fact that Add replaces existing items, we
// can just add new map in place of the old one
totalmap.Add(index, newAtIndex)
如评论中所述,如果您正在学习函数式编程,那么最好的方法是使用不可变的数据结构——在这里,您可以使用一个映射,将索引映射到嵌套映射(其中包含您需要的键值信息) 尝试使用以下示例:
// Add new item (key, num pair) to the map at the specified index
// Since totalMap is immutable, this returns a new map!
let addData index (key:int) (num:int) (totalmap:Map<_, Map<_, _>>) =
// We are assuming that the value for index is defined
let atIndex = totalmap.[index]
let newAtIndex =
// Ignore information if it is already there, otherwise add
if atIndex.ContainsKey key then atIndex
else atIndex.Add(key, num)
// Using the fact that Add replaces existing items, we
// can just add new map in place of the old one
totalmap.Add(index, newAtIndex)
您确定地图中确实有多个不同的词典,而不仅仅是对同一词典的多个引用吗?您确定地图中确实有多个不同的词典,而不仅仅是对同一词典的多个引用吗?