我正在寻找创建一个函数,它接受一个值,在字典中找到值,然后删除它,同时也通过字典并使值的键后来少一个,就像这样(值的键)在字典中是从1和向上的int值):
let deleteitem (item: Gitem) =
let mutable count = 1
while count<=invendict.Count do
let testitem = invendict.Item[count]
if item = testitem then
invendict.Remove[count]
//from here, look at every value, whos key is higher than the key of
the removed value, and decreases the key by one, till every value is looked at
根据示例中的代码片段,看起来字典中的键只是字典中的索引(因为代码示例中的循环从1
迭代到invendict.Count
)。在这种情况下,使用字典是一个坏主意。你可以使用ResizeArray
(这是.NET通用可变List<T>
类型的F#类型别名)。
从ResizeArray
中删除项目正是您需要的行为:
let r = ResizeArray ["A";"B";"C"]
r.RemoveAt(1) // Remove the B element
r.[0] // Returns A as before removal
r.[1] // Returns C which was at 2 before the removal
如果你真的想使用字典,那么你基本上需要创建一个新字典 - 重新创建字典可能比删除和添加一半元素更有效。