如何从字典中删除项目并更改其他人的密钥F#

问题描述 投票:0回答:1

我正在寻找创建一个函数,它接受一个值,在字典中找到值,然后删除它,同时也通过字典并使值的键后来少一个,就像这样(值的键)在字典中是从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
dictionary f#
1个回答
3
投票

根据示例中的代码片段,看起来字典中的键只是字典中的索引(因为代码示例中的循环从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

如果你真的想使用字典,那么你基本上需要创建一个新字典 - 重新创建字典可能比删除和添加一半元素更有效。

© www.soinside.com 2019 - 2024. All rights reserved.