Pseudo Nym Pseudo Nym - 7 months ago 48 Question

Generating a List of object properties from a pre-existing list VB.Net

With a python background, I've become rather accustomed to using lines like

print(" ".join({ for x in my_list}))


{ for x in my_list}

is a list/array containing the name property of each of the objects in my_list.

I'm looking to do something similar in VB.Net, I know this is possible using a longer section of code like:

Dim str1 = ""
For each item in myList
str1 &= & " "

But I'd much prefer a simpler solution as I'll be doing this a lot, and I've heard there's similar notation possible using LINQ.

Any help would be appreciated.

Answer Source

I think you talking about IEnumerable(Of T).Select function. Which you can use for mapping collection of one type to collection of another type.

Dim combinedNames As String = String.Join(" ", myList.Select(Function(item) item.Name))

So equivalent for python's { for x in my_list} in will be

Dim names = myList.Select(Function(item) item.Name)

Dim builder = new StringBuilder()
For Each name in names
    builder.Append(" ")

Dim allNames = builder.ToString()

Notice that Select function return IEnumerable(Of T) type.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download