【问题标题】:How can I add an item to IEnumerable(Of T) in VB.NET?如何在 VB.NET 中向 IEnumerable(Of T) 添加项目?
【发布时间】:2009-09-11 06:21:34
【问题描述】:

我看到了一些关于在 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,但这会导致我运行时崩溃。我错过了什么?

【问题讨论】:

    标签: vb.net


    【解决方案1】:

    一种选择是编写一个连接单个元素的扩展方法

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

    【讨论】:

      【解决方案2】:

      你不能 Concat 单个元素和一个序列 - 你 Concat 两个序列在​​一起,基本上。

      您有三个选择:

      • 从单个元素构建序列(例如,单个元素数组)
      • 编写一个库方法来做你想做的事(在没有迭代器块的 VB9 中可能会很棘手)
      • 使用MoreLinq,已经是has this functionality

      使用 MoreLinq 选项,您可以调用以下任一方法:

      item.Concat(sequence)
      sequence.Prepend(item)
      

      首先产生单个项目,或

      sequence.Concat(item)
      

      最后产生单个项目。

      (回想起来,我不确定我是否喜欢item.Concat版本;它添加的扩展方法过于广泛。我们可能会删除它。)

      【讨论】:

      • 很好的答案。我对 item.Concat 也有疑问,尤其是 Prepend 做同样的事情。如果我是你,我会删除它;-)
      猜你喜欢
      • 2010-11-15
      • 2013-08-22
      • 2014-07-29
      • 1970-01-01
      • 2010-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多