开发者

VB.NET: Prepend a string to all strings in a list of strings. Is there an existing method that does this?

开发者 https://www.devze.com 2023-01-10 20:48 出处:网络
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.

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 A开发者_运维技巧s 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.


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.


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)


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

String.Insert


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();


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 :)

0

精彩评论

暂无评论...
验证码 换一张
取 消