In einem vorangegangenem Post habe ich eine Extension vorgestellt, die eine ConfigurationElementCollection in ein IEnumerable<T> umwandelt. Darauf aufbauend stelle ich hier eine eine weitere Erweiterungsmethode vor, die eine NameValueConfigurationCollection in ein Dictionary umwandelt.

Meine erste Implementierung erzeugt aus der NameValueConfigurationCollection ein Dictionary<string, string>, was mir am gebräuchlichsten erscheint.

public static Dictionary<string, string> ToDictionary(
  this NameValueConfigurationCollection collection)
{
  IEnumerable<NameValueConfigurationElement> elements;
  elements = collection.AsEnumerable<NameValueConfigurationElement>();

  return (from e in elements select e).ToDictionary(e => e.Name, e => e.Value);
}

Denkbar ist allerdings auch eine Variante, die eine andere Typisierung erlaubt…

public static Dictionary<TKey, TValue> ToDictionary<TKey, TValue>(
  this NameValueConfigurationCollection collection)
{
  IEnumerable<NameValueConfigurationElement> elements;
  elements = collection.AsEnumerable<NameValueConfigurationElement>();

  Type keyType = typeof(TKey);
  TypeConverter keyConverter = TypeDescriptor.GetConverter(keyType);

  Type valueType = typeof(TValue);
  TypeConverter valueConverter = TypeDescriptor.GetConverter(valueType);

  return (from e in elements select e).ToDictionary(
    e => (TKey) keyConverter.ConvertFrom(e.Name),
    e => (TValue) valueConverter.ConvertFrom(e.Value));
 }

Damit wäre dann Folgendes möglich…

using System.Configuration;
...
NameValueConfigurationCollection collection = new NameValueConfigurationCollection();

collection.Add(new NameValueConfigurationElement("1", "B044EAF2-8B6A-42b4-8CDE-84B2249E89FB"));

Dictionary<Int32, Guid> result = collection.ToDictionary<Int32, Guid>();

Guid id = result[1];
...