HashSet的使用索引访问 [英] HashSet with Index Access

查看:1322
本文介绍了HashSet的使用索引访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要的


    的数据结构
  1. 允许我补充/项目给它

  2. 不允许重复

  3. 通过索引访问集合

我想HashSet的,但 HashSet中没有索引。什么是满足上述需求的数据结构

I am thinking about hashset, but HashSet doesn't have an index. What is the data structure that fulfills the above need?

推荐答案

如何从的 KeyedCollection< TKEY的,TItem> 的?这表示,其中每个键是从产品本身衍生项的集合。默认情况下它不会允许你添加重复(即项目使用相同的密钥)。它允许通过键索引查找。

How about a collection derived from KeyedCollection<TKey, TItem>? 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<string, TestItem>
    {
        public TestItemCollection()
        {
        }

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

这篇关于HashSet的使用索引访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆