3

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"

Rod
  • 14,529
  • 31
  • 118
  • 230
  • http://stackoverflow.com/a/1998049/139698 - I like the following solution but I didn't understand the comments made about possible performance using string builder. so i did some searching and found the following and implemented it: http://www.csharp411.com/c-convert-string-to-stream-and-stream-to-string/ - Was this what the comments were referring to? – Rod May 26 '12 at 04:59

3 Answers3

4
var headers = this.GetType().GetProperties().Select(p => p.Name).Aggregate((p1, p2) => p1 + "," + p2);
phixed
  • 478
  • 2
  • 7
2

You can use the TypeDescriptor class (which is more efficient than plain reflection):

string.Join(",", TypeDescriptor.GetProperties(instance).Select(p => p.Name))
Lucero
  • 59,176
  • 9
  • 122
  • 152
1
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.

Chris
  • 971
  • 7
  • 15