tags:

views:

76

answers:

2

I see a couple of previously answered questions about adding an item to an IEnumerable in C#, but I'm stuck when trying to implement the proposed solution in 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"})

The above code gives the error:

Option Strict On disallows implicit conversions from Customer to IEnumerable(Of Customer)

VS2008 then suggests using CType, but that results in a runtime crash for me. What am I missing?

+3  A: 

You can't Concat a single element with a sequence - you Concat two sequences together, basically.

You have three options:

  • Build a sequence from your single element (e.g. a single-element array)
  • Write a library method to do what you want (could be tricky in VB9, which doesn't have iterator blocks)
  • Use MoreLinq, which already has this functionality

With the MoreLinq option, you can call either of:

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

to yield the single item first, or

sequence.Concat(item)

to yield the single item last.

(Looking back on it, I'm not sure I like the item.Concat version; it adds the extension method too widely. We may remove it.)

Jon Skeet
Great answer. I have doubts too about item.Concat, especially with Prepend doing the same thing. I would remove it if I was you ;-)
Meta-Knight
I think we will, yes.
Jon Skeet
+3  A: 

One option is to write an extension method which concats a single element

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