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)?
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);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With