将ConfigurationElementCollection内部的对象的属性复制到数组吗?

时间:2018-09-28 17:33:20

标签: c# .net custom-configuration

我创建了一个自定义配置部分,可以向我的自定义部分添加尽可能多的XML行,然后遍历并打印所有这些行。很好。

<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>

我遵循了有关配置自定义配置的指南,并为我的ConfigurationSection创建了ConfigurationElementCollection。

我的最终目标遍历ConfigurationElementCollection(包含上面的3个XML节点),然后将所有“ Customer”属性添加到字符串数组。

我无法弄清楚该怎么做,因为即使ConfigurationElementCollection从ICollection和IEnumberable派生,我也无法访问Select()或Where()方法。谁能提供解决方案?

如果需要,我可以提供代码。我以为先放在这里太麻烦了。

编辑:这是我尝试投射的2种不同方式

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

错误文字:

  

无法隐式转换类型   “ System.Collections.Generic.IEnumerable”为“ string []”。一个明确的   转换存在(您是否缺少演员表?)。

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

错误文字:

  

对象不包含“客户”的定义,也不可访问   扩展方法“客户”接受类型的第一个参数   可以找到“对象”。

ANSWER FOUND: :我能够将ToArray()方法添加到数组定义的末尾,并且可以与Haukinger的代码一起使用!谢谢!

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

1 个答案:

答案 0 :(得分:2)

先发布IEnumerable<object>,然后再Select您需要的内容

您可以直接投射((IEnumerable<object>))或使用linq的Cast<object>()。大部分linq可在IEnumerable<T>而不是IEnumerable上工作。