Tôi giả sử rằng bạn đang mở rộng một loại từ điển không cho phép khóa douplicate.
Điều gì về việc triển khai này. Tôi giả sử rằng mục của bạn thực hiện IComparable.
class BaseSortedCollection<T> : Collection<T>, ICollection<T>, IEnumerable<T>,
System.Collections.ICollection, System.Collections.IEnumerable
where T : IComparable<T>
{
/// <summary>
/// Adds an item to the Collection<T> at the correct position.
/// </summary>
/// <param name="item">The object to add to </param>
public new void Add(T item)
{
int pos = GetInsertPositio(item);
base.InsertItem(pos, item);
}
/// <summary>
/// Convinience function to add variable number of items in one Functioncall
/// </summary>
/// <param name="itemsToBeAdded">The items to be added.</param>
/// <returns>this to allow fluent interface</returns>
public AutoSortCollection<T> AddItems(params T[] itemsToBeAdded)
{
foreach (var item in itemsToBeAdded)
Add(item);
return this;
}
/// <summary>
/// Get position where item should be inserted.
/// </summary>
/// <param name="item"></param>
/// <returns>Get position where item should be inserted.</returns>
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;
}
}
này nên làm việc (sử dụng MSTest)
/// <summary>
///A test sorting for SCCPackageEx Constructor
///</summary>
[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 + "]");
}
tôi cảm thấy khó khăn để đưa ra lời khuyên tốt mà không biết một số chi tiết thi hành BaseSortedCollection của bạn. Tại sao các bản sao không hoạt động ở vị trí đầu tiên? Tại sao không sử dụng cây nhị phân (có thể cân bằng) làm cấu trúc dữ liệu cho các mục của bạn? – Lucero
Cảm ơn bạn đã trả lời. Các bản sao không hoạt động vì hai mục có cùng ItemID, đó là những gì đang được sử dụng làm khóa trong bộ sưu tập. –