Reputation: 15433
Environment: asp.net fx3.5
given
public class Product
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public decimal UnitPrice { get; set; }
}
i have a List<Product>
collection.
is there a way to get the property names because i want them to be a header row in my csv file that i'm constructing?
so the result i'm looking for is a string = "ProductId,ProductName,UnitPrice"
Upvotes: 3
Views: 13613
Reputation: 60190
You can use the TypeDescriptor
class (which is more efficient than plain reflection):
string.Join(",", TypeDescriptor.GetProperties(instance).Select(p => p.Name))
Upvotes: 2
Reputation: 1001
String.Join(",", typeof(Product).GetProperties().Select(p => p.Name))
If you don't want to use Linq, you can just iterate through the PropertyInfo array returned by GetProperties and concatenate the names to a string.
Upvotes: 1
Reputation: 488
var headers = this.GetType().GetProperties().Select(p => p.Name).Aggregate((p1, p2) => p1 + "," + p2);
Upvotes: 4