C#의 HASHTable 구현의 예는 무엇입니까?
문제
일반적으로 C#과 .NET에는 이미 해시 가능 및 사전 클래스가 있다는 것을 알고 있습니다.
누구든지 C#에서 해시 가능의 구현을 시연 할 수 있습니까?
업데이트: 명확히하기 위해, 나는 완전한 구현을 찾고 있지 않고, 해시 테이블의 핵심 기능의 예입니다 (즉, 추가, 제거, 키에 의해 찾기).
해결책
물론 클래스 라이브러리의 모노 버전도 있습니다.
다른 팁
질문이 질문을받은 후에도 많은 담당자를 얻을 것으로 기대하지 않습니다. 그러나 나는 내 자신의 기본적인 예를 작성하는 것이 재미있을 것이라고 결정했습니다 (90 줄 미만의 코드).
public struct KeyValue<K, V>
{
public K Key { get; set; }
public V Value { get; set; }
}
public class FixedSizeGenericHashTable<K,V>
{
private readonly int size;
private readonly LinkedList<KeyValue<K,V>>[] items;
public FixedSizeGenericHashTable(int size)
{
this.size = size;
items = new LinkedList<KeyValue<K,V>>[size];
}
protected int GetArrayPosition(K key)
{
int position = key.GetHashCode() % size;
return Math.Abs(position);
}
public V Find(K key)
{
int position = GetArrayPosition(key);
LinkedList<KeyValue<K, V>> linkedList = GetLinkedList(position);
foreach (KeyValue<K,V> item in linkedList)
{
if (item.Key.Equals(key))
{
return item.Value;
}
}
return default(V);
}
public void Add(K key, V value)
{
int position = GetArrayPosition(key);
LinkedList<KeyValue<K, V>> linkedList = GetLinkedList(position);
KeyValue<K, V> item = new KeyValue<K, V>() { Key = key, Value = value };
linkedList.AddLast(item);
}
public void Remove(K key)
{
int position = GetArrayPosition(key);
LinkedList<KeyValue<K, V>> linkedList = GetLinkedList(position);
bool itemFound = false;
KeyValue<K, V> foundItem = default(KeyValue<K, V>);
foreach (KeyValue<K,V> item in linkedList)
{
if (item.Key.Equals(key))
{
itemFound = true;
foundItem = item;
}
}
if (itemFound)
{
linkedList.Remove(foundItem);
}
}
protected LinkedList<KeyValue<K, V>> GetLinkedList(int position)
{
LinkedList<KeyValue<K, V>> linkedList = items[position];
if (linkedList == null)
{
linkedList = new LinkedList<KeyValue<K, V>>();
items[position] = linkedList;
}
return linkedList;
}
}
작은 테스트 응용 프로그램은 다음과 같습니다.
static void Main(string[] args)
{
FixedSizeGenericHashTable<string, string> hash = new FixedSizeGenericHashTable<string, string>(20);
hash.Add("1", "item 1");
hash.Add("2", "item 2");
hash.Add("dsfdsdsd", "sadsadsadsad");
string one = hash.Find("1");
string two = hash.Find("2");
string dsfdsdsd = hash.Find("dsfdsdsd");
hash.Remove("1");
Console.ReadLine();
}
최상의 구현은 아니지만 추가, 제거 및 찾기에 적합합니다. 사용합니다 체인 적절한 버킷을 찾기위한 간단한 모듈로 알고리즘.
당신은 C5 컬렉션? 당신은 할 수 있습니다 소스를 다운로드하십시오 해시 테이블이 포함됩니다.
반사기를 사용하여 .net hashtable이 구현되는 방법 (예 : C#)을 볼 수 있습니다.
간단한 '성장 전용'해시 테이블을 볼 수 있습니다 여기, 간단한 구현에 대한 아이디어를 제공해야합니다.
면책 조항 : 코드에는 몇 가지 버그가있을 수 있지만 원칙은 동일합니다 :)
당신은 또한 Hashtable 구현을 볼 수도 있습니다 단핵증 여기:
제휴하지 않습니다 StackOverflow