我猜你正在扩展一种不允许重复键的字典。
那么这个实现怎么样?我假设你的Item实现了IComparable接口。
class BaseSortedCollection<T> : Collection<T>, ICollection<T>, IEnumerable<T>,
System.Collections.ICollection, System.Collections.IEnumerable
where T : IComparable<T>
{
public new void Add(T item)
{
int pos = GetInsertPositio(item);
base.InsertItem(pos, item);
}
public AutoSortCollection<T> AddItems(params T[] itemsToBeAdded)
{
foreach (var item in itemsToBeAdded)
Add(item);
return this;
}
private int GetInsertPositio(T item)
{
if (item == null)
throw new ArgumentNullException();
for (int pos = this.Count - 1; pos >= 0; pos--)
{
if (item.CompareTo(this.Items[pos]) > 0)
return pos + 1;
}
return 0;
}
}
这应该可以工作(使用MsTest)
[TestMethod()]
public void SortingTest()
{
BaseSortedCollection<int> collection = new BaseSortedCollection<int>().AddItems(1,5,3,2,4,0);
Assert.AreEqual(6, collection.Count, "collection.Count");
for(int i=0; i <=5; i++)
Assert.AreEqual(i, collection[i], "collection[" + i + "]");
}