另外需要添加一個RemoveAt方法:
// 移除指定索引元素
public void RemoveAt(int index)
{
if ((index < 0) || (index >= this._size))
{
throw new ArgumentOutOfRangeException ("index", "Index out of range");
}
this._size--;
if (index < this._size)
{
Array.Copy(this.keys, (int)(index + 1), this.keys, index,
(int)(this._size - index));
Array.Copy(this.values, (int)(index + 1), this.values, index,
(int)(this._size - index));
}
this.keys[this._size] = default (TKey);
this.values[this._size] = default(TValue);
this.version++;
}
最後,進行測試,這一次 不再使用int做為鍵,而改用string:
static void Main()
{
ReversibleSortedList<string, string> rs = new ReversibleSortedList<string, string>();
//添加元素
rs.Add("3", "a");
rs.Add("1", "b");
rs.Add ("2", "c");
rs.Add("6", "d");
rs.Add("5", "e");
rs.Add("4", "f");
//使用 DictionaryEntry打印鍵/值
foreach (KeyValuePair<string, string> d in rs)
{
Console.WriteLine (d.Key + " " + d.Value);
}
Console.WriteLine("刪除索引為“2”的“5”的元 素");
rs.Remove("2");
rs.Remove("5");
foreach (KeyValuePair<string, string> d in rs)
{
Console.WriteLine(d.Key + " " + d.Value);
}
}
ReversibleSortedList 0.7版本:實現 IDictionary<TKey, TValue>接口
運行結果:
1 b
2 c
3 a
4 f
5 e
6 d
刪除索引為“2”的“5”的元素
1 b
3 a
4 f
6 d
本文配套源碼