3

I want to use a KeyedCollection to store a class against a string key value. I have the following code:

public class MyClass
{
    public string Key;
    public string Test;
}

public class MyCollection : KeyedCollection<string, MyClass>
{
    public MyCollection() : base()
    {
    }

    protected override String GetKeyForItem(MyClass cls)
    {
        return cls.Key;
    }
}

class Program
{
    static void Main(string[] args)
    {
        MyCollection col = new MyCollection();
        col.Add(new MyClass()); // Here is want to specify the string Key Value
    }
}

Can anyone tell me what I’m doing wrong here? Where do I specify the key value so that I can retrieve by it?

Paul Michaels
  • 16,185
  • 43
  • 146
  • 269

3 Answers3

8

Your GetKeyForItem override is what specifies the key for an item. From the docs:

Unlike dictionaries, an element of KeyedCollection is not a key/value pair; instead, the entire element is the value and the key is embedded within the value. For example, an element of a collection derived from KeyedCollection<String,String> might be "John Doe Jr." where the value is "John Doe Jr." and the key is "Doe"; or a collection of employee records containing integer keys could be derived from KeyedCollection<int,Employee>. The abstractGetKeyForItem` method extracts the key from the element.

So in order for the item to be keyed correctly, you should set its Key property before adding it to the collection:

MyCollection col = new MyCollection();
MyClass myClass = new MyClass();
myClass.Key = "This is the key for this object";
col.Add(myClass); 
AakashM
  • 62,551
  • 17
  • 151
  • 186
  • +1 - for researching and answering the question rather than simply saying 'use a Dictionary' - which is probably what I would've said. – Andras Zoltan Jun 30 '10 at 08:24
1

The KeyedCollection is a base class for creating keyed collections, so there is quite a lot that you need to implement yourself.

Perhaps using a Dictionary would be easier and faster to work with.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • Although Dictionary for general purposes is the preferred approach; KeyedCollections allow you to load an object into a collection where a member in the object is the key to the value of the collection. – GoldBishop Jul 16 '18 at 15:51
0

I know it's slightly different, but have you considered implementing an indexer.

public string this[string index]
{
    get { 
      // put get code here
    }
    set {
      // put set code here.
    }
}
Jonathan
  • 25,873
  • 13
  • 66
  • 85