【问题标题】:Copy properties of objects inside ConfigurationElementCollection to an array?将 ConfigurationElementCollection 中对象的属性复制到数组中?
【发布时间】:2021-02-21 15:40:46
【问题描述】:

我创建了一个自定义配置部分,可以将尽可能多的 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 派生自 ICollectionIEnumerable,我也无法访问 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);
}

错误:

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

找到答案:我能够将 ToArray&lt;string&gt;() 方法添加到数组定义的末尾,并且它与 Haukinger 的代码一起使用!谢谢!

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

【问题讨论】:

    标签: c# .net custom-configuration


    【解决方案1】:

    投射到IEnumerable&lt;object&gt; 然后Select 你需要什么

    您可以直接投射 ((IEnumerable&lt;object&gt;)) 或使用 linq 的 Cast&lt;object&gt;()。大多数 linq 适用于 IEnumerable&lt;T&gt; 而不是 IEnumerable

    【讨论】:

    • 投射我的 ConfigurationElementCollection?谢谢我会试试这个。我查看了 ConfigurationElementCollection 的定义,它已经派生自 ICollection 和 IEnumerable 所以这就是我感到困惑的原因。
    • 直接转换集合对象无法访问 Select()。使用 Cast() 让我更接近一点,但存在转换错误。我将使用 2 种不同的技术和错误文本更新问题。
    • 添加 .ToArray() 这个 Cast() 方法有效!谢谢你是天才。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-25
    • 1970-01-01
    • 2019-09-18
    • 2019-08-21
    • 2022-01-18
    • 2019-11-14
    相关资源
    最近更新 更多