Brent Arias
Brent Arias

Reputation: 30155

Dictionary Using Value Property as Key

Back around 2008 I was using a BCL dictionary that established the key based on a property of the obect-value that it was storing. Now I can't find that dictionary. Can someone remind me? Here is what I recall about it:

I tried using a reflector tool to find all dictionary classes throughout the BCL, and I didn't spot it. Perhaps the word "Dictionary" was not in the name of this magical class I had once been using.

Upvotes: 5

Views: 169

Answers (1)

NathanAldenSr
NathanAldenSr

Reputation: 7961

Perhaps you are remembering the KeyedCollection<,> abstract class? It established a key based on anything you want from the item.

public class MyObject
{
    public string Key
    {
        get;
        set;
    }

    public int Foo
    {
        get;
        set;
    }
}

public class MyObjectCollection : KeyedCollection<string, MyObject>
{
    protected override string GetKeyForItem(MyObject item)
    {
        return item.Key;
    }
}

In practice, I find LINQ's ToDictionary() to be more useful, though.

http://msdn.microsoft.com/en-us/library/ms132438(v=vs.110).aspx

Upvotes: 5

Related Questions