Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define custom titles on properties of objects

Tags:

c#

I have a list of objects of some class defined as

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
} 

var personList = new List<Person>();
personList.Add(new Person
   {
        FirstName = "Alex",
        LastName = "Friedman",
        Age = 27
   });

and output that list as a table with property name as a column header (full source code)

var propertyArray = typeof(T).GetProperties();
foreach (var prop in propertyArray)
     result.AppendFormat("<th>{0}</th>", prop.Name);  

and get

FirstName  | LastName  | Age
----------------------------------
Alex         Friedman    27

I want to have some custom titles, like

First Name | Last Name | Age 

Question: How to define column titles for each property of the Person class? Should I use custom attributes on properties or is there any better way?

like image 629
user2316116 Avatar asked Oct 18 '22 02:10

user2316116


1 Answers

This is an approach i'd do in your case. It's quite simple and self explaining:

 var propertyArray = typeof(T).GetProperties();
      foreach (var prop in propertyArray) { 
        foreach (var customAttr in prop.GetCustomAttributes(true)) {
          if (customAttr is DisplayNameAttribute) {//<--- DisplayName
            if (String.IsNullOrEmpty(headerStyle)) {
              result.AppendFormat("<th>{0}</th>", (customAttr as DisplayNameAttribute).DisplayName);
            } else {
              result.AppendFormat("<th class=\"{0}\">{1}</th>", headerStyle, (customAttr as DisplayNameAttribute).DisplayName);
            }
            break;
          }
        }

      }

Since the linked extensionmethod uses Reflection anyway, you can just modify the Header-Formatting loop like above.

The Usage of the Attribute will look like this:

public class Person {
    [DisplayName("First Name")]
    public string FirstName {
      get; set;
    }

    [DisplayName("Last Name")]
    public string LastName {
      get; set;
    }
    public int Age {
      get; set;
    }
  }
like image 55
lokusking Avatar answered Nov 15 '22 05:11

lokusking