我需要一個數據結構,HashSet的使用索引訪問
- 允許我補充/項目以
- 不允許重複
- 經指數
我訪問集合我正在考慮hashset,但HashSet doesn't have an index。什麼是滿足上述需求的數據結構?
我需要一個數據結構,HashSet的使用索引訪問
我訪問集合我正在考慮hashset,但HashSet doesn't have an index。什麼是滿足上述需求的數據結構?
我想你想要的是一個Dictionary。
它工作嗎?
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();
}
}
}
來自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;
}
}
}
我認爲你需要開發自己的List
擴展類。 List
可以匹配您的第1點和第3點,但要匹配第2點,您需要覆蓋Add
方法。
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();
}
}
}
}
如果你不綁定到特定的.NET版本,@bobbymcr有可能是很好的答案;-) – Seb