Brian Surowiec Brian Surowiec -4 years ago 229
C# Question

Is there a generic alternative to the ListDictionary class?

I was looking at some sample code and in it they used a

ListDictionary
object to store a small amount of data (around 5-10 objects or so, but this number could change over time). The only issue I have with using this class is that, unlike everything else I've been doing, it's not generic. This means, and correct me if I'm wrong here, that every time I get an object out of here or enumerate over it that there's casting going on. Is there enough overhead in the larger
Dictionary<T>
object to justify the overhead of a non-generic
ListDictionary
?

The code that will be using this object will be enumerated over on each page load which I'm guessing is why the
ListDictionary
class was used over one of the other alternatives. This is also why I would like the most performance out of this list of data.

Answer Source

Unfortunately there is no generic equivalent of ListDictionary.

However it shouldn't be terribly difficult to implement one. ListDictionary essentially works by keeping a linked list of Key/Value pairs and iterating over them for lookup operations. You could build a ListDictionary<TKey,TValue> by wrapping a LinkedList<T> with some very simply LINQ expressions.

For example

public class LinkedDictionary<TKey,TValue> {
  private LinkedList<KeyValuePair<TKey,TValue>> _list = new LinkedList<KeyValuePair<TKey,TValue>>();
  private IEqualityComparer<TKey> _comp = EqualityComparer<TKey>.Default;

  public void Add(TKey key, TValue value) { 
    _list.Add(new KeyValuePair<TKey,TValue>(key,value)); 
  }
  public TValue Get(TKey key) {  
    return _list.Where(x => _comp.Equals(x.Key,key)).First().Value;
  }
  ...
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download