如何在VB.NET中向IEnumerable(Of T)添加项?

如何在VB.NET中向IEnumerable(Of T)添加项?,vb.net,Vb.net,在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"}) 上述代码给

在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不允许从Customer到IEnumerable(Of Customer)的隐式转换


VS2008建议使用CType,但这会导致运行时崩溃。我遗漏了什么?

你不能
Concat
带有序列的单个元素-你基本上可以
Concat
两个序列在一起

您有三种选择:

  • 从单个元素(例如,单个元素数组)构建序列
  • 编写一个库方法来执行您想要的操作(在没有迭代器块的VB9中可能很棘手)
  • 使用,它已经
使用MoreLinq选项,您可以调用以下任一选项:

item.Concat(sequence)
sequence.Prepend(item)
首先生成单个项目,或

sequence.Concat(item)
最后一项


(回头看,我不确定我是否喜欢
item.Concat
版本;它添加了太多的扩展方法。我们可能会删除它。)

一个选项是编写一个包含单个元素的扩展方法

<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"})
_
公共函数ConcatSingle(Of T)(ByVal e作为IEnumerable(Of T),ByVal elem作为IEnumerable(Of T)
Dim arr As T()=新的T(){elem}
返回e.Concat(arr)
端函数
...
customers=customers.ConcatSingle(具有{.Name=“John Smith”}的新客户)

回答得很好。我对这个项目也有怀疑,尤其是Prepend也在做同样的事情。如果我是你,我会把它拿走;-)