带索引访问的HashSet

时间:2011-10-18 07:15:12

标签: c# hashset

我需要一个

的数据结构
  1. 允许我添加/项目
  2. 不允许复制
  3. 通过索引
  4. 访问该集合

    我正在考虑hashset,但是HashSet doesn't have an index。什么是满足上述需求的数据结构?

5 个答案:

答案 0 :(得分:3)

KeyedCollection<TKey, TItem>派生的集合怎么样?这表示项目的集合,其中每个键都是从项目本身派生的。默认情况下,它不允许您添加重复项(即具有相同键的项)。它允许按键索引进行查找。

internal class Program
{
    private static void Main(string[] args)
    {
        TestItemCollection items = new TestItemCollection();
        items.Add(new TestItem("a"));
        items.Add(new TestItem("a")); // throws ArgumentException -- duplicate key

        TestItem a = items["a"];
        a = items[0];
    }

    private sealed class TestItem
    {
        public TestItem(string value)
        {
            this.Value = value;
        }

        public string Value { get; private set; }
    }

    private sealed class TestItemCollection : KeyedCollection<string, TestItem>
    {
        public TestItemCollection()
        {
        }

        protected override string GetKeyForItem(TestItem item)
        {
            return item.Value;
        }
    }
}

答案 1 :(得分:1)

有效吗?

class MyHashSet<T> : HashSet<T>
{
    public T this[int index]
    {
        get
        {
            int i = 0;
            foreach (T t in this)
            {
                if (i == index)
                    return t;
                i++;
            }
            throw new IndexOutOfRangeException();
        }
    }
}

答案 2 :(得分:0)

我认为你想要的是Dictionary

答案 3 :(得分:0)

我认为你需要开发自己的List扩展类。 List可以匹配您的第1点和第3点,但要匹配第2点,您需要覆盖Add方法。

答案 4 :(得分:-1)

You can do it by extending the HashSet, meat of it to see if it contains the element, and thats O(1), reaturn that  element, so no harm done in that case. Here is the derived one:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;

namespace Tester
{
    // Summary:
    //     Represents a set of values.
    //
    // Type parameters:
    //   T:
    //     The type of elements in the hash set.
    [Serializable]
    public class HashSetExt<T> : HashSet<T>
    {
        // Summary:
        //     Initializes a new instance of the System.Collections.Generic.HashSetExt<T> class
        //     that is empty and uses the default equality comparer for the set type.
        public HashSetExt() : base() { }

        public HashSetExt(IEnumerable<T> collection) : base(collection) { }
        public HashSetExt(IEqualityComparer<T> comparer) : base(comparer) { }

        public HashSetExt(IEnumerable<T> collection, IEqualityComparer<T> comparer) : base(collection, comparer) { }

        protected HashSetExt(SerializationInfo info, StreamingContext context) : base(info, context) { }

        public T this[T item]
        {
            get
            {
                if (this.Contains(item))
                {
                    return item;
                }
                throw new KeyNotFoundException();
            }
        }
    }
}