views:

52

answers:

1

i want to take a list of anonymous types and export then to excel. I have the code to export to excel if i have the data, but i want to be able write some generic code to:

Loop through all of the fields in the anonymous type so i can export it to excel. I would like to keep the ordering if possible as well.

+4  A: 

I happen to have some code which does almost exactly that...

The ordering of properties isn't guaranteed via reflection, but the constructor parameters are. So you can fetch the names via the constructor parameters, and then fetch the properties from there.

Here's a blog post which uses anonymous types for nullity checks... but basically you'd do the same steps as this bit in the middle, but fetching the values instead. Note that I use a generic class to let me do the reflection bit just once - after that I've got delegates to fetch the values, and a list of names.

Jon Skeet