Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a general concrete implementation of a KeyedCollection?

The System.Collections.ObjectModel.KeyedCollection class is a very useful alternative to System.Collections.Generic.Dictionary, especially when the key data is part of the object being stored or you want to be able to enumerate the items in order. Unfortunately, the class is abstract, and I am unable to find a general concrete implementation in the core .NET framework.

The Framework Design Guidlines book indicates that a concrete implementation should be provided for abstract types (section 4.4 Abstract Class Design). Why would the framework designers leave out a general concrete implementation of such a useful class, especially when it could be provided by simply exposing a constructor that accepts and stores a Converter from the item to its key:

public class ConcreteKeyedCollection<TKey, TItem> : KeyedCollection<TKey, TItem>
{
    private Converter<TItem, TKey> getKeyForItem = null;
    public ConcreteKeyedCollection(Converter<TItem, TKey> getKeyForItem)
    {
        if (getKeyForItem == null) { throw new ArgumentNullException("getKeyForItem"); }
        this.getKeyForItem = getKeyForItem;
    }
    protected override TKey GetKeyForItem(TItem item)
    {
        return this.getKeyForItem(item);
    }
}
like image 210
Kevin Kibler Avatar asked Dec 03 '09 20:12

Kevin Kibler


1 Answers

There are concrete implementations, including (but not limited to):

  • KeyedByTypeCollection<TItem> (I use this class frequently)
  • MessageHeaderDescriptionCollection

To the spirit of your question, no there is no generic implementation and since I do not work for Microsoft I could only speculate. Since the concrete implementation is as easy as you've shown, I won't offer any speculation (as it would probably be wrong).

like image 74
user7116 Avatar answered Sep 18 '22 19:09

user7116