Search code examples
c#.netcustom-configuration

Copy properties of objects inside ConfigurationElementCollection to an array?


I created a custom configuration section and can add as many XML lines to my custom section and loop through and print them all. That works fine.

<eTMSoftware>
    <Program Id="1" Customer="SomeCust" Type="DC" InstalledLocation="C:\Program Files (x86)\eMenuDesktopComponent 1.1.1.1_Customer" LogBaseDestination="C:\_eTM Logging"/>
    <Program Id="2" Customer="ThisCustNew" Type="DC" InstalledLocation="Some_Path" LogBaseDestination="DEST"/>
    <Program Id="3" Customer="AnotherNewCust" Type="DC" InstalledLocation="Some_Another_Path" LogBaseDestination="DEST"/>
</eTMSoftware>

I followed a guide on configuring custom configuration and I created a ConfigurationElementCollection for my ConfigurationSection.

My end goal: loop through the ConfigurationElementCollection (which contains the 3 XML nodes above) and add all of the Customer attributes to a string array.

I cannot figure out how to do this, because even though ConfigurationElementCollection derives from ICollection and IEnumerable, I don't have access to the Select() or Where() methods.

Can anyone offer a solution?

I can supply code if needed. I thought It would be too much to put here at first.

Edit: here are 2 different ways I tried casting

public void VerifyShareDestinationsPerCustomer(eTMProgamsElementCollection configuredItems)
{
     string[] customersFromConfig = configuredItems.Cast<eTMProgramElement>()
                                                   .Select(p => p.Customer);
}

Error:

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'string[]'. An explicit conversion exists (Are you missing a cast?).

public void VerifyShareDestinationsPerCustomer(eTMProgamsElementCollection configuredItems)
{
     string[] customersFromConfig = configuredItems.Cast<object>()
                                                   .Select(p => p.Customer);
}

Error:

Object does not contain a definition for 'Customer' and no accessible extension method 'Customer' accepting a first argument of type 'Object' could be found.

ANSWER FOUND: I was able to add ToArray<string>() method to the end of the array definition and it worked with code from Haukinger! Thanks!

string[] customersFromConfig = configuredItems.Cast<eTMProgramElement>()
                                              .Select(p => p.Customer)
                                              .ToArray<string>();

Solution

  • Cast to IEnumerable<object> then Select what you need

    You can either cast directly ((IEnumerable<object>)) or use linq's Cast<object>(). Most of linq works on IEnumerable<T> and not IEnumerable.