c# - 在 SortedDictionary 中找到第一个未使用的键的快速方法?

标签 c# .net key sorteddictionary

如果我有一个 SortedDictionary<int, object> , 找到当前未使用的最低键的最快方法是什么?显然,我们可以从 0-> int.MaxValue 迭代一个计数器 i如果 !Keys.Contains(i) 则转义,但这会非常慢,除非我们很幸运并且第一个备用 key 恰好在 key 序列的早期。也许甚至不同的 .NET 类已经为我们做了这个?

最佳答案

因此,如果我没理解错的话,键可以是从 0int.MaxValue 的任何位置。在这种情况下,您必须找到键序列中的第一个“洞”。

这应该可以有效地完成工作:

public static int GetFirstUnusedKey<TValue>(SortedDictionary<int, TValue> dict)
{
    if (dict.Comparer != Comparer<int>.Default)
        throw new NotSupportedException("Unsupported comparer");

    using (var enumerator = dict.GetEnumerator())
    {
        if (!enumerator.MoveNext())
            return 0;

        var nextKeyInSequence = enumerator.Current.Key + 1;

        if (nextKeyInSequence < 1)
            throw new InvalidOperationException("The dictionary contains keys less than 0");

        if (nextKeyInSequence != 1)
            return 0;

        while (enumerator.MoveNext())
        {
            var key = enumerator.Current.Key;
            if (key > nextKeyInSequence)
                return nextKeyInSequence;

            ++nextKeyInSequence;
        }

        return nextKeyInSequence;
    }
}

我添加了一些检查以确保先决条件有效。

关于c# - 在 SortedDictionary 中找到第一个未使用的键的快速方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27689234/

相关文章:

database - 如何快速获取 leveldb 中的确切键数?

C# MVC Controller 调用两次

c# - 从 C# 类中提取数据属性显示名称?

c# - 面板上的矩形区域以捕获鼠标输入

.net - .NET 4.7.2 如何管理在 .NET Standard 2.0 中编译的依赖项的重定向?

c# - 第二台显示器/电视下的 WPF 主窗口的屏幕截图

c# - 如何判断一个key是字母还是数字?

C# Regex 使用 newLine 在两个字符串之间查找字符串

c# - 安装程序与。桌面应用程序

javascript - 如何为数组中的每个对象提供自己的键?