2016-12-27 16 views
-1

我想優化這段代碼:VB.Net - 充分利用收集的物品,而無需使用循環

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

(PolNo的數據類型爲String)

我試圖用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]'. 

回答

0

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)界面來完成。

+0

謝謝!我需要將mPolNo的數據類型從Collection(Of String)更改爲List(Of String)以使其運行。 –