次に自動的に取得されたキーに追加するための Extension メソッドでSortedListを使用できます。
データ構造が数値キーを持つ任意のオブジェクトであると仮定すると、
以下はSortedListのExtensionMethodです
public static class SortedListExtensions
{
///Add item to sortedList (numeric key) to next available key item, and return key
public static int AddNext<T>(this SortedList<int, T> sortedList, T item)
{
int key = 1; // Make it 0 to start from Zero based index
int count = sortedList.Count;
int counter=0;
do
{
if (count == 0) break;
int nextKeyInList = sortedList.Keys[counter++];
if (key != nextKeyInList) break;
key = nextKeyInList +1;
if (count == 1 || counter == count ) break;
if (key != sortedList.Keys[counter])
break;
} while (true);
sortedList.Add(key, item);
return key;
}
}
次のように使用できます
SortedList<int, string> x = new SortedList<int, string>();
x.Add(4, "BCD");
x.Add(6, "BCD");
x.AddNext("a");
x.AddNext("b");
x.AddNext("c");
x.AddNext("d");
x.AddNext("e");
foreach (var item in x)
Console.WriteLine(item.Key + " " + item.Value);
出力は
1 a
2 b
3 c
4 BCD
5 d
6 BCD
7 e
ディクショナリまたはその他のデータ構造を使用できます。その場合は二重ループが必要になります。SortedList の場合、キーを検索する際のループが 1 回節約されます。このループはSortedList.Add
BinarySearch Algorithm を使用する関数によって内部的に使用されます。
バイナリ検索は、すべての要素をループするよりも高速です (より大きなサイズのデータの場合)。