views:

59

answers:

5

I have a list of strings. For each string in that list, I want to prepend another string. I wrote a method to do it, but I was wondering if there was something already in .NET I could use to do this. It seems like something that could be built in, but I was not able to find anything.

Here is the method I wrote:

Private Function PrependToAllInList(ByRef inputList As List(Of String), ByRef prependString As String) As List(Of String)
    Dim returnList As List(Of String) = New List(Of String)
    For Each inputString As String In inputList
        returnList.Add(String.Format("{0}{1}", prependString, inputString))
    Next
    Return returnList
End Function

It works, but I would rather use built in functions whenever possible. Thanks for your help.

+5  A: 

If you can use LINQ (.NET 3.5 or greater), you can use a simple LINQ query to do the work for you:

Dim qry = stringList.Select(Function(s) "prepend this " & s)
Dim returnList = qry.ToList()

By default, Select() will return an IEnumerable(Of String), which should work. If you really need the collection to be a list, you can include the .ToList() command. However, if you only plan to iterate over the collection (e.g. For Each s As String in qry), there's no need to take on the expense of converting it back to a list.

Ben McCormack
This worked great. Thanks! I have not used LINQ before, so I did not think to look there.
Jeremy
@Jeremy LINQ is great! Any time you would use a `For Each` loop, you can probably use `LINQ`. Check out [101 LINQ Samples](http://msdn.microsoft.com/en-us/vbasic/bb688088.aspx).
Ben McCormack
Thanks for the link.
Jeremy
A: 
returnList = strlistList.Aggregate(New List(Of String), _
                 Function(list, s) list.Add("prepend this " & s) )

(note, I'm a C# prog, so I'm not sure about the syntax)

James Curran
A: 

What you are talking about is a mapping function, I've not come across any predefined mapping functions in vb.net, but you could achieve this in either the manner you have or using a lambda expression, delegates or LINQ.

There's a great blog post here on use of delegates for this purpose at http://www.panopticoncentral.net/archive/2006/12/08/18587.aspx

The joy of this is it'll work in .NET 2.0 - but it's not nearly as elegant as LINQ which can be used in 3.5 and up...

inputList.Select(Function(s) String.Format("{0}{1}", pre, s).ToList();
BenAlabaster
A: 

You could use String.Insert instead of your String.Format to get it closer to what you expected.

String.Insert

Iain M Norman
A: 

As an aside, you can use string.concat to concatenate two strings, rather than string.format.

So instead of

String.Format("{0}{1}", prependString, inputString)

you could just put

String.Concat(prependString, inputString)

...as you seem keen to keep your code as clean as possible :)

Fiona Holder
Thanks for the tip on String.Concat.
Jeremy