So, if I understand you correctly, the keys can be from 0to int.MaxValue. In this case, you need to find the first "hole" in the key sequence.
This should do the job efficiently:
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;
}
}
I added a couple of checks to make sure the assumptions are valid.
source
share