Saturday, March 29, 2008

There is a nice little base class hidden inside System.Collections.ObjectModel namespace. Its name is KeyedCollection. Its there to solve all those situations when we need a collection where items are to be unique, a "collection whose keys are embedded in the values" - as MSDN describes it.

As nice as the class is, there is one problem. It is abstract. The reason it is abstract is the GetKeyForItem method. For each type what we need a unique collection, we need to create a new class, inherit it from the KeyedCollection and override that one method. I think that's a bit of a waste of time and needles complexity in most cases. Fortunately, there is hope.

Enter KCollection. The idea behind it is to use Lambda Expressions where we had to override the GetKeyForItem method before. Sample code should explain everything:

class KCollection<TKey, TItem>  : KeyedCollection<TKey, TItem>
{
    Func<TItem, TKey> getKey;
    public KCollection(Func<TItem, TKey> getKey)
    {
        this.getKey = getKey;
    }
    protected override TKey GetKeyForItem(TItem item)
    {
        return getKey(item);
    }
}

And usage looks as follows:

KCollection<int, Client> kcol = new KCollection<int, Client>(c => c.Id);

Where Client is a simple class:

class Client
{
    public int Id;
    public string Name;
}

Of course we could achieve similar functionality using .NET 2.0 and delegates, I think Lambda Expressions are just nicer.

Monday, August 04, 2008 2:39:45 AM (Central European Standard Time, UTC+01:00)
awesomeness. thanks for the tip!
Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, strike) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview