Is there a way in c# to loop over the properties of a class?
Basically I have a class that contains a large number of property’s (it basically holds the results of a large database query).
I need to output these results as a CSV file so need to append each value to a string.
The obvious way it to manually append each value to a string, but is there a way to effectively loop over the results object and add the value for each property in turn?
Sure; you can do that in many ways; starting with reflection (note, this is slowish – OK for moderate amounts of data though):
However; for larger volumes of data it would be worth making this more efficient; for example here I use the
ExpressionAPI to pre-compile a delegate that looks writes each property – the advantage here is that no reflection is done on a per-row basis (this should be significantly faster for large volumes of data):