SortedCollection (C#, 2.0)에서 허용 된 복제물 필요
-
06-09-2019 - |
문제
중복을 허용하기 위해 'BasesortedCollection'클래스를 변경 해야하는 프로젝트가 있습니다. 이 클래스는 현재 ienumerable, idisposable, icollection 및 iserializable을 구현합니다. 'BasesortedCollection'은 컬렉션에 액세스 할 때 키로 사용되는 itemid (int64)가있는 항목을 저장합니다. 컬렉션에 동시에 동일한 두 가지 항목 (동일한 itemId)이 동시에 존재하고 검색 할 수 있어야합니다.
우리는 2.0 프레임 워크를 사용하고 있습니다.
제안이 있습니까?
미리 감사드립니다!
해결책
자동 정렬이 필요한 경우 일반 Arraylist를 확장하고 Add-Method를 대신하여 전화를 걸어야한다고 생각합니다. 그러나 나는 동일한 (고유 한) 식별 번호로 두 항목의 아이디어를 주위에 머리를 감싸지 못하는 것 같습니다!
편집, 또는 아마도 system.collections. Specialized)에서 편집 또는 NameValueCollection이 더 적절합니까? 확장하고 자신의 정렬 방법을 추가하십시오 ...
다른 팁
베이스 소환의 각 항목은 목록 (t) 일 수 있으므로 키가 동일한 두 개의 항목이있는 경우 해당 키에 해당하는 항목에 두 개의 항목이 포함 된 목록 (t)이 있습니다.
나는 당신이 Doupsic Keys를 허용하지 않는 일종의 사전을 확장하고 있다고 가정합니다.
이 구현은 어떻습니까. 나는 당신의 품목이 상징적 인 것을 구현한다고 가정합니다.
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;
}
}
이것은 작동해야합니다 (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 + "]");
}