开发者

how can you loop through all fields of an anonymous type

开发者 https://www.devze.com 2023-01-07 07:01 出处:网络
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:

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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消