需要允许在SortedCollection重复(C#,2.0)
-
06-09-2019 - |
题
我有我的工作,一个项目需要改变“BaseSortedCollection”类,允许重复。类目前实现IEnumerable,IDisposable接口,ICollection的,和ISerializable的。在“BaseSortedCollection”存储的项目具有的项目ID(Int64类型),其访问该集合时用作密钥。我需要有两个相同的项目(相同的ItemID)在同一时间集合中存在以及能够被检索。
我们使用的是2.0框架。
任何建议?
提前感谢!
解决方案
我想你将不得不延长一个普通的ArrayList,并覆盖加载方法,如果您需要自动分拣到排序打电话。不过,我似乎无法换我周围的两个项目的想法头相同的(我应该是唯一的)识别号码?!
修改,或也许NameValueCollection中(在System.Collections.Specialized)是比较合适的?扩展它,并添加自己的排序方法...
其他提示
在您的BaseSortedCollection每个项目可能是一个List(T),所以如果你有相同的密钥两个项目,你将有一个包含两个项目对应于该键的条目列表(T)。
我假设你是延伸的一种字典,不允许douplicate键。
这个实现什么。我假设你的项目实现了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;
}
}
这应该工作(使用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 + "]");
}
不隶属于 StackOverflow