简体   繁体   中英

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:

  • It required the class that was used as the <value> to implement an interface which had a method or property that identified which field/member was to be considered the key.
  • It was a dictionary being used or defined in one of the ServiceModel namespaces.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM