Adding and Retrieving from KeyedCollection

I want to use KeyedCollection to store a class by the value of a string key. 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 someone tell me what I'm doing wrong here? Where to specify the key value so that I can get it?

+3
source share
3 answers

Your override GetKeyForItemis what the key indicates for the element. From the docs:

, KeyedCollection /; , . , , KeyedCollection<String,String>, "John Doe Jr." "John Doe Jr." "Doe"; , , KeyedCollection<int,Employee>. The abstract GetKeyForItem`, .

, Key, :

MyCollection col = new MyCollection();
MyClass myClass = new MyClass();
myClass.Key = "This is the key for this object";
col.Add(myClass); 
+8

KeyedCollection - , .

, Dictionary .

+1

, , , indexer.

public string this[string index]
{
    get { 
      // put get code here
    }
    set {
      // put set code here.
    }
}
0

Source: https://habr.com/ru/post/1752407/


All Articles