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

标签 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"})

上面的代码给出了错误:

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/

相关文章:

.net - 如何在 vb.net 中创建辅助消息循环?

c# - ASP.NET:如何在 GridView 中显示从数据库返回的不同值

.net - 我在哪里可以获得有关 ! VB.Net 在 Linq to DataSet 中使用的运算符?

c# - Windows 服务每周运行一次

asp.net - 在 VB.Net 中将 gridview 导出为 excel 不采用提供的文件名?

xml - 如何使用 VB .net 解析 XML

vb.net - 抛出异常后如何继续运行代码?

asp.net - RDLC:本地报告处理期间发生错误

asp.net - 从 gridview 中的文本框获取之前的值

c# - .NET 中的字符串标记