Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve ConfigurationElement using key (array key access) in ConfigurationCollection?

I need to do something like this on my custom configuration section:

ConfigurationManager.ConnectionStrings["mongodb"]

The string "mongodb" above is the key that I am using to access de element of type System.Configuration.ConnectionStringSettings. I wish to do the same with my custom collection:

[ConfigurationCollection(typeof(Question))]
public class QuestionCollection : ConfigurationElementCollection
{   

    public override bool IsReadOnly()
    {
        return false;
    }

    protected override ConfigurationElement CreateNewElement()
    {
        return new Question();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        return ((Question)element).id;
    }

    //Is here?
    public Question this[int idx]
    {
        get {
            return (Question)BaseGet(idx);
        }

        set
        {
            if (BaseGet(idx) != null)
                BaseRemoveAt(idx);

            BaseAdd(idx, value);
        }
    }

}

I was wondering that method commented above is the way to get what I want... But I don't know how.... The type of key I want use to access is integer.

Supposing I have the following configuration:

    <securityQuestions>
    <questions>
      <add id="3" value="What is your name?" default="true"/>
      <add id="4" value="What is your age?"/>
    </questions>
</securityQuestions>

How can I access the first element (id=3) with ...Section.Questions[3] (3 is not the position, but the key)?

like image 497
Lucas Batistussi Avatar asked Oct 11 '13 02:10

Lucas Batistussi


1 Answers

Thanks to Aleksei Chepovoi for the sugestions. The solution is as follows:

[ConfigurationCollection(typeof(Question))]
public class QuestionCollection : ConfigurationElementCollection
{   

    public override bool IsReadOnly()
    {
        return false;
    }

    protected override ConfigurationElement CreateNewElement()
    {
        return new Question();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        return ((Question)element).id;
    }

    public Question this[int id]
    {
        get
        {
           return this.OfType<Question>().FirstOrDefault(item => item.id == id);
        }
    }

}
like image 104
Lucas Batistussi Avatar answered Oct 04 '22 21:10

Lucas Batistussi