Is there a .net framework method to generate a collection from a property of all items in a collection?
I have
myObjects = List(of myObject)
myObject has
Public Property myProperty as string
Is there a framework method to produce
myObjectProperties = List(of string)
开发者_如何学JAVAfrom each myObject.myProperty
in myObjects
?
Obviously I can easily create one. I'm just wondering if there's a framework solution.
Linq:
myObjectProperties = myObjects.Select(x => x.myProperty).ToList()
(sorry, it's C# and not VB.NET, but you are just talking about .NET ...)
And here's the VB version of @Stefan Steinegger's code:
Dim myObjectProperties = myObjects.Select(Function(F) F.myProperty).ToList()
In addition to the LINQ solution posted by others, you can use also use the ConvertAll
instance method on the List(Of T)
class to eagerly create a new list based on a projection.
Dim myObjectProperties = myObjects.ConvertAll(Function(m) m.myProperty)
精彩评论