Prabhu
Prabhu

Reputation: 13325

Convert class properties into a list of strings

How do you convert the names of public properties of a class into a list of strings? Syntax preferably in VB.NET.

I was trying to do something like this:

myClassObject.GetType().GetProperties.ToList()

However, I need a List(Of String)

Upvotes: 7

Views: 19079

Answers (2)

Lee
Lee

Reputation: 144126

var propertyNames = myClassObject.GetType().GetProperties().Select(p => p.Name).ToList();

Or if you know the type you want to use in advance, you can do:

var propertyNames = typeof(ClassName).GetProperties().Select(p => p.Name).ToList();

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1499760

Getting the name of each property? Use LINQ to project each PropertyInfo using the LINQ Select method, selecting the MemberInfo.Name property.

myClassObject.GetType().GetProperties().Select(p => p.Name).ToList()

Or in VB, I think it would be:

myClassObject.GetType.GetProperties.Select(Function (p) p.Name).ToList

Upvotes: 21

Related Questions