【问题标题】:VB.Net - Getting an item from collection without using loopVB.Net - 从集合中获取项目而不使用循环
【发布时间】:2016-12-27 10:16:39
【问题描述】:

我想优化这段代码:

dim mPolNo as new Collection(Of String)
For Each _olap As clsOLAP in cscOLAPs
     mPolNo.Add(_olap._p1.PolNo)
Next

(PolNo的数据类型为String)

我尝试使用我在 google 中挖掘的 Collection.Select。

mPolNo = cscOLAPs.Select(Function(x) x._p1.PolNo.ToString)

但我遇到错误提示:

Unable to cast object of type 'WhereSelectEnumerableIterator`2[SIPLib.ING.clsOLAP,System.String]' to type 'System.Collections.ObjectModel.Collection`1[System.String]'.

【问题讨论】:

    标签: string vb.net linq collections lambda


    【解决方案1】:

    Where 返回IEnumerable(Of String)
    要将其分配给Collection(Of String),您需要枚举Where 的结果。

    可以通过调用.ToList()扩展方法来完成

    cscOLAPs.Select(Function(x) x._p1.PolNo.ToString).ToList()
    

    ToList() 可以使用,因为Collection(Of String) 实现了IList(Of String) 接口。

    【讨论】:

    • 谢谢!我需要将 mPolNo 的数据类型从 Collection(Of String) 更改为 List(Of String) 以使其运行。
    猜你喜欢
    • 1970-01-01
    • 2013-04-16
    • 2017-01-24
    • 2021-08-14
    • 1970-01-01
    • 2020-02-05
    • 2018-12-20
    • 1970-01-01
    • 2015-11-01
    相关资源
    最近更新 更多