2009-09-11 56 views
1

我看到了一些以前回答的关于在C#中向IEnumerable添加项目的问题,但是我在尝试在VB.NET中实现建议的解决方案时遇到困难。如何在VB.NET中添加项目到IEnumerable(Of T)?

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,但导致运行时坠毁我。我错过了什么?

回答

4

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

你有三个选择:

  • 建立从您的单个元素的序列(例如单元素数组)
  • 写库的方法做你想做的(可能在VB9,会非常棘手,这没有迭代器块)
  • 使用MoreLinq,已经has this functionality

随着MoreLinq选项,你可以调用的:

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

先得到单个项目,或

sequence.Concat(item) 

到最后得到单个项目。

(回想起来,我不知道我喜欢item.Concat版本;它增加了扩展方法过于广泛,我们可以将其删除。)

+0

很好的答案。我也怀疑item.Concat,特别是Prepend做同样的事情。如果我是你,我会删除它;-) – 2009-09-11 12:59:33

+0

我想我们会的,是的。 – 2009-09-11 13:28:36

5

一种选择是写一个concats一个扩展方法单个元素

<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"}) 
相关问题