Using Linq with a non-Linq Collection

Recently I needed to extract some data from a custom Configuration Collection. I really like LINQ but this is a non LINQ collection and the idea of writing extra code to get at this stuff seemed too much like hard work.

Fortunately the Custom Configuration class supports the IEnumerable interface which in turn supports the Cast method to transform the collection into a generic collection (and thus one that supports LINQ).

Given a configuration class like this:


public class ProxyDomainConfiguration : ConfigurationSection
    {
        /// <summary>
        /// Returns an MarketSet.RegionHomepageConfiguration instance
        /// </summary>
        public static ProxyDomainConfiguration GetConfig()
        {
            return ConfigurationManager.GetSection("RCHProxyDomainConfiguration") as ProxyDomainConfiguration;
        }

        [ConfigurationProperty("domains")]
        public ProxyDomainConfigurationCollection Domains
        {
            get
            {
                return this["domains"] as ProxyDomainConfigurationCollection;
            }
        }
     }

I can get the first entry that matches my LINQ criteria with a further trivial piece of code:


var pdc = ProxyDomainConfiguration.GetConfig();
var groupSite = from domain in 
        pdc.Domains.Cast<ProxyDomainConfigurationElement>().Where(domain =>domain.IsGroupSite == true)
        select domain;

return groupSite.FirstOrDefault().Domainprefix.ToLowerInvariant();