Haben Sie schon einmal versucht, Elemente einer ConfigurationElementCollection via LINQ abzufragen? Dann haben Sie sicher festgestellt, das dies nicht ohne Weiteres möglich ist, da die ConfigurationElementCollection-Klasse das IEnumerable<T>-Interface nicht implementiert. Zur Lösung des Problems kann die folgende Extension eingesetzt werden…
public static IEnumerable<T> AsEnumerable<T>(this ConfigurationElementCollection collection)
{
foreach (T element in collection)
yield return element;
}
Es folgt nun ein kurzes Beispiel zur Verwendung…
using System.Configuration;
...
public class CustomConfigurationElement : ConfigurationElement
{
public CustomConfigurationElement() : base() { }
[System.Configuration.ConfigurationProperty("key", IsKey=true)]
public string Key { get; set; }
}
...
class Program
{
static void Main()
{
CustomConfigurationElementCollection customCollection;
customCollection = new CustomConfigurationElementCollection();
customCollection.Add(new CustomConfigurationElement() { Key = "abc" });
customCollection.Add(new CustomConfigurationElement() { Key = "123" });
var elements = (from e in customCollection.AsEnumerable<CustomConfigurationElement>()
where "abc".Equals(e.Key) select e);
foreach (var element in elements)
Console.WriteLine(element.Key);
}
}

1 Trackback or Pingback for this entry:
[...] } In einem vorangegangenem Post habe ich eine Extension vorgestellt, die eine ConfigurationElementCollection in ein [...]