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"

4

3 回答 3

4
var headers = this.GetType().GetProperties().Select(p => p.Name).Aggregate((p1, p2) => p1 + "," + p2);
于 2012-05-26T00:11:06.667 回答
2

您可以使用TypeDescriptor该类(比普通反射更有效):

string.Join(",", TypeDescriptor.GetProperties(instance).Select(p => p.Name))
于 2012-05-26T00:16:14.303 回答
1
String.Join(",", typeof(Product).GetProperties().Select(p => p.Name))

如果您不想使用 Linq,您可以遍历 GetProperties 返回的 PropertyInfo 数组并将名称连接到一个字符串。

于 2012-05-26T00:11:52.570 回答