我需要一个数据结构
- 允许我向其中添加/项目
- 不允许重复
- 通过索引访问集合
我正在考虑哈希集,但是HashSet没有索引。满足上述需求的数据结构是什么?
源自的集合怎么样KeyedCollection?这表示项目的集合,其中每个键都源自项目本身。默认情况下,它不允许您添加重复项(即具有相同键的项目)。它允许通过键查找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;
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)