我看到一些之前回答过的有关在 C# 中向 IEnumerable 添加项目的问题,但在尝试在 VB.NET 中实现建议的解决方案时遇到了困难。
Option Strict On
Dim customers as IEnumerable(Of Customer)
' Return customers from a LINQ query (not shown)
customers = customers.Concat(New Customer with {.Name = "John Smith"})
上面的代码给出了错误:
Option Strict On disallows implicit conversions from Customer to IEnumerable(Of Customer)
VS2008 然后建议使用 CType,但这会导致我运行时崩溃。我错过了什么?
最佳答案
一种选择是编写一个连接单个元素的扩展方法
<Extension()> _
Public Function ConcatSingle(Of T)(ByVal e as IEnumerable(Of T), ByVal elem as T) As IEnumerable(Of T)
Dim arr As T() = new T() { elem }
Return e.Concat(arr)
End Function
...
customers = customers.ConcatSingle(New Customer with {.Name = "John Smith"})
关于vb.net - 如何在 VB.NET 中向 IEnumerable(Of T) 添加项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1409272/