Reputation: 1640
How can I get list of properties of a object/class using linq??
public class Person {
public string Name { get; set; }
public string Age { get; set; }
public string Gender { get; set; }
}
I want to {"Name","Age","Gender"}.
Upvotes: 1
Views: 5093
Reputation: 2676
typeof(Person).GetProperty("Name")
You can get the individual properties using Reflection. For more details read here.
Upvotes: 0
Reputation: 6627
As a previous commenter mentioned, reflection is the tool you should use to acquire this information.
Following is a small example program that will retrieve and display the property names from a hypthetical "Person" class:
System.Type type = typeof(Person);
System.Reflection.PropertyInfo[] properties = type.GetProperties();
foreach (System.Reflection.PropertyInfo property in properties)
Console.WriteLine(property.Name);
Upvotes: 3
Reputation: 1358
You will need to use reflection. Here's a function that I have used on many projects.
private List<MemberInfo> GetMembers(Type objectType, MemberTypes memberType)
{
List<MemberInfo> members = new List<MemberInfo>();
Assembly asm = Assembly.GetAssembly(objectType);
foreach (Type t in asm.GetExportedTypes().Where((Type testType) => object.ReferenceEquals(testType, objectType))) {
foreach (MemberInfo mi in t.GetMembers().Where((MemberInfo member) => member.MemberType == memberType)) {
switch (memberType) {
case MemberTypes.Property:
members.Add(mi);
break;
case MemberTypes.Method:
bool isValid = true;
foreach (PropertyInfo pi in t.GetProperties()) {
if ((pi.CanWrite && pi.GetSetMethod().Name == mi.Name) || (pi.CanRead && pi.GetGetMethod().Name == mi.Name)) {
isValid = false;
break;
}
}
if (isValid)
members.Add(mi);
break;
}
}
}
return members.OrderBy((MemberInfo mi) => mi.Name).ToList();
}
To call it, you can use, for example:
var properties = GetMembers(typeof(myObject), MemberTypes.Property)
Upvotes: 1