I want to generate an HTML table from a couple specified parameters. Specifically, the two parameters I want to pass into my method are: IEnumerable list, and some subset of properties of T. For example, let's say I have a List of this class:
class Person
{
string FirstName
string MiddleName
string LastName
}
Let's say the list has 5 people in it. I want to be able to get an HTML table of that class (or any other arbitrary class) by doing something like this:
List<Person> people;
...add people to list
string HTML = GetMyTable(people, "FirstName", "LastName");
I'm sure there's a better way to specify which properties I want the table generated from (or which properties I want excluded from the table, that would be better since I'll usually want most or all of the class's properties), but I'm not sure how (I've never used reflection, but I'm guessing that's how). Also, the method should accept a list of any type of class.
Any clever ideas on how to accomplish this?
Here are two approaches, one using reflection:
Or using lambdas:
With the lambdas, what's happening is you're passing methods to the
GetMyTable
method to get each property. This has benefits over reflection like strong typing, and probably performance.This is what I did and it seems to work fine and not a huge performance hit.
To use it just pass the ToHtmlTable() a List Example:
List documents = GetMyListOfDocuments(); var table = documents.ToHtmlTable();
Maybe something like this?
--Version 2.0--
PS: Calling
fxn.Compile()
repeatedly can be performance killer in a tight loop. It can be better to cache it in a dictionary .Good luck with
Extention Method
Using
Result