중복 키를 허용하지 않는 사전을 확장한다고 가정합니다.
이 구현은 어떨까요? 귀하의 Item은 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;
}
}
이 내가 어려운 당신 BaseSortedCollection의 일부 구현 세부 사항을 알고 있기없이 좋은 조언을 줄 것을 발견
/// <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 + "]");
}
출처
2010-12-09 12:31:16
k3b
(MSTEST을 사용하여) 작동합니다. 중복이 처음부터 작동하지 않는 이유는 무엇입니까? 아이템에 대한 데이터 구조로 (아마도 밸런싱 된) 이진 트리를 사용하지 않으시겠습니까? – Lucero
답변 해 주셔서 감사합니다. 두 개의 항목이 동일한 ItemID를 가지고 있기 때문에 복제본이 작동하지 않습니다. 이는 컬렉션의 키로 사용되는 항목입니다. –