2

I have a task that I am sure can be easily generalized in a simple way.

I have different tables to be exported to excel dynamically, and what I am doing is creating the table columns in HTML from the Object parameters, and the rows using a foreach on the List to create the rows.

So for example if I have a list of Customer (List<Customer> ) I create the tr basing on the amount and name of the Object properties:

public class Customer
{
    public int DeliveryAddressId { get; set; }
    public DateTime CreatedDate { get; set; }
    public string Firstname { get; set; }
    public string Lastname { get; set; }
    ....
}

var output = "<table>";
        output += "<thead>";
        output += "<tr>";
        output += "<th>DeliveryAddressId </th>";
        .....

and the foreach to fill in the rows:

foreach (var customer in List<Customer>)
        {
            output += "<tr>";
            output += "<td>" + customer.DeliveryAddressId + "</td>";
            .....

But then I have different objects with different parameters, so the question is:

How can I create a generic method that takes a List<Object> as input and create this kind of table using the object parameter names as columns name and then cycles the rows accordingly?

1 Answer 1

4

If you create a generic method that accepts a list of T

public string DumpToTable<T>(List<T> list) {
}

You could enumerate all public properties on T like so:

var props = typeof(T).GetProperties(BindingFlags.Public);

Depending on your use case, you might want to make that .GetProperties(BindingFlags.Public | BindingFlags.DeclaredOnly); to filter out inherited members.

For each PropertyInfo element, you can then access their .Name, when generating the header.

After that, iterating through the list, you'd have to invoke their relative .GetValue methods:

foreach(T item in list) {
    string line = "";
    foreach(PropertyInfo prop in props) {
         line += string.Format("<td>{0}</td>", prop.GetValue(item));
    }
    output += string.Format("<tr>{0}</tr>", line);
}
Sign up to request clarification or add additional context in comments.

1 Comment

The sweetness I was looking for. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.