HashSet with Index Access

后端 未结 5 1415
轻奢々
轻奢々 2021-01-07 11:58

I would need a data structure that

  1. Allows me to add/item to it
  2. Do not allow duplication
  3. access the collection via index

I am t

5条回答
  •  温柔的废话
    2021-01-07 12:52

    How about a collection derived from KeyedCollection? This represents a collection of items where each key is derived from the item itself. By default it does not allow you to add duplicates (i.e. items with the same key). It allows lookup by key or index.

    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
        {
            public TestItemCollection()
            {
            }
    
            protected override string GetKeyForItem(TestItem item)
            {
                return item.Value;
            }
        }
    }
    

提交回复
热议问题