Example code :
EDITED : clarified example. Sorry for any confusion.
using System.Collections.Specialized;
using System.Configuration;
...
// get collection 1
NameValueCollection c1 = ConfigurationManager.AppSettings;
// get collection 2
ExeConfigurationFileMap map = new ExeConfigurationFileMap();
map.ExeConfigFilename = "c:\\SomeConfigFile.config";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
KeyValueConfigurationCollection c2 = config.AppSettings.Settings;
// do something with collections
DoSomethingWithCollection(c1);
DoSomethingWithCollection(c2);
...
private void DoSomethingWithCollection(KeyValueConfigurationCollection c)
{
foreach(KeyValueConfigurationElement el in c)
{
string key = el.Key;
string val = el.Value;
// do something with key and value
}
}
private void DoSomethingWithCollection(NameValueCollection c)
{
for(int i=0; i < c.Count; i++)
{
string key = c.GetKey(i);
string val = c.Get(i);
// do something with key and value
}
}
There are currently two versions of DoSomethingWithCollection to take either a NameValueCollection or KeyValueConfigurationCollection.
Is there a cleaner way of doing this, so that there is just one version of DoSomethingWithCollection ?
Thanks.
Well, DoSomethingWithCollection should accept two parameters – 1) ICollection/IEnumerable that will allow you to enumerate through all values 2) Delegate that will take the object and give you key and value back. So you need to essentially write two different methods to parse the item for both type of collections.
Edit: A sample code to give an idea.
Edit 2: Not sure what you mean by not needing a delegate – if you need to have one version of DoSomethingWithCollection, you need to have at least some code that work different across both collection. Delegate would be the simplest way. Another way would be define an interface that will provide a collection/enumeration of NamedValuePair/KeyValuePair and then write to wrapper classes implementing this interface for different kind of target collections. Template code would be
IMO, a too much work for a simple requirement.