Dictionary with key based on stored data

What is the easiest way to create a dictionary that will be bound to a property of a data object? For instance. imagine that I have:

interface A
{
  string Key{get;}
  //other stuff
}

So far I:

IDictionary<string, A> dict = new Dictionary<string, A>();
void Add(A a)
{
  dict[a.Key] = a; //I would prefer that the collection class managed this relationship
}

A Get(string key)
{
  return dict[key];
}

Is there a better way to achieve the same? (the assembly does not need to implement an IDictionary if it has the required index).

+3
source share
1 answer

You can use KeyedCollection:

public class MyCollection : KeyedCollection<string, A>
{
    protected override GetKeyForItem(A a)
    {
        return a.Key;
    }
}
+5
source

All Articles