есть своя реализация dictionary:
public class MyDictionary<TKey, TValue> : IEnumerable<KeyValuePair<TKey,TValue>>
{
private int _count;
private Node<TKey, TValue>[] _storage;
private readonly int _currentSize;
private const int DefaultSize = 100;
public MyDictionary(int size)
{
_currentSize = size;
_storage = new Node<TKey, TValue>[size];
}
public MyDictionary()
{
_currentSize = DefaultSize;
_storage = new Node<TKey, TValue>[DefaultSize];
}
public int Count()
{
return _count;
}
public void Add(TKey key, TValue value)
{
if (ContainsKey(key))
{
throw new ArgumentException($"Dictionary already contain this key: {key}");
}
var pos = GetPosition(key);
Add(pos, key, value);
_count++;
}
public bool ContainsKey(TKey key)
{
foreach (var node in _storage)
{
if ( node != null && node.Next != null)
{
var tmp = node;
while (tmp != null)
{
if (tmp.Key.Equals(key))
{
return true;
}
tmp = tmp.Next;
}
}
if (node != null && node.Key.Equals(key))
{
return true;
}
}
return false;
}
public bool ContainsValue(TValue value)
{
foreach (var node in _storage)
{
if (node?.Next != null)
{
var tmp = node;
while (tmp != null)
{
if (tmp.Value.Equals(value))
{
return true;
}
tmp = tmp.Next;
}
}
if (node != null && node.Value.Equals(value))
{
return true;
}
}
return false;
}
public void Remove(TKey key)
{
if (!ContainsKey(key))
{
throw new ArgumentException($"Dictionary not contain the value with key: {key}");
}
var pos = GetPosition(key);
if (_storage[pos].Next == null)
{
_storage[pos] = null;
_count--;
return;
}
var tmp = _storage[pos];
_storage[pos] = null;
while (tmp != null)
{
if (!tmp.Key.Equals(key))
{
Add(pos, tmp.Key, tmp.Value);
}
tmp = tmp.Next;
}
_count--;
}
public void Clear()
{
_storage = new Node<TKey, TValue>[_currentSize];
_count = 0;
}
private void Add(int pos, TKey key, TValue value)
{
if (_storage[pos] != null)
{
var tmp = _storage[pos];
while (tmp.Next != null)
{
tmp = tmp.Next;
}
tmp.Next = new Node<TKey, TValue>() { Key = key, Value = value };
}
else
{
_storage[pos] = new Node<TKey, TValue>() { Key = key, Value = value };
}
}
private int GetPosition(TKey key)
{
return Math.Abs(key.GetHashCode() % _currentSize);
}
public IEnumerator<KeyValuePair<TKey, TValue>> Enumerator()
{
foreach (var node in _storage)
{
if (node == null) continue;
if (node.Next != null)
{
var current = node;
while (current != null)
{
yield return new KeyValuePair<TKey, TValue>(current.Key, current.Value);
current = current.Next;
}
}
else
{
yield return new KeyValuePair<TKey, TValue>(node.Key, node.Value);
}
}
}
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return Enumerator();
}
public IEnumerator GetEnumerator()
{
return Enumerator();
}
}
internal class Node<TKey, TValue>
{
public TValue Value { get; set; }
public TKey Key { get; set; }
public Node<TKey, TValue> Next;
}
и при проходе по нему с помощью foreach он возвращает object вместо KeyValuePair подскажите в чем проблема