需要在已排序集合中允许重复项吗?(C#,2.0)

7
我正在处理一个项目,需要修改“BaseSortedCollection”类以允许重复项。该类目前实现了IEnumerable、IDisposable、ICollection和ISerializable接口。'BaseSortedCollection'存储具有ItemID(Int64)的项,该项在访问集合时用作键。我需要在集合中同时存在两个相同的项(具有相同的ItemID),并且能够检索这两个项。
我们使用的是2.0框架。
您有什么建议吗?
提前感谢!

1
我发现在不了解你的BaseSortedCollection的一些实现细节的情况下很难给出好的建议。为什么重复项一开始就不能正常工作呢?为什么不使用(可能是平衡的)二叉树作为项目的数据结构? - Lucero
感谢您的回复。重复项无法正常工作,因为两个项目具有相同的ItemID,而该ID是在集合中用作键。 - Chris
3个回答

5

你的BaseSortedCollection中每个条目都可以是List(T),因此如果你有两个具有相同键的条目,则将为对应该键的条目包含两个条目的List(T)。


我更喜欢使用Collection(T)而不是List(T),因为List会允许myList[20] = someItem这样的操作,这将破坏排序。请参见我的回复。 - k3b

0

我猜你正在扩展一种不允许重复键的字典。

那么这个实现怎么样?我假设你的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;
    }
}

这应该可以工作(使用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 + "]");
    }

-1

我想你需要扩展一个常规的ArrayList,覆盖Add方法以便如果需要自动排序则调用Sort方法。但是,我无法理解两个具有相同(应该是唯一的)标识号的项目的概念?!

或许编辑一下,使用System.Collections.Specialized中的NameValueCollection可能更合适? 扩展它并添加自己的排序方法...


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接