Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you loop over the properties of a class?

Tags:

c#

reflection

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?

like image 484
Sergio Avatar asked Nov 25 '10 11:11

Sergio


People also ask

Which loop is used to loop through an object properties?

for...in Loop The most straightforward way to loop through an object's properties is by using the for...in statement. This method works in all modern and old browsers including Internet Explorer 6 and higher.

How do I copy values from one object to another in C#?

In general, when we try to copy one object to another object, both the objects will share the same memory address. Normally, we use assignment operator, = , to copy the reference, not the object except when there is value type field. This operator will always copy the reference, not the actual object.


1 Answers

Sure; you can do that in many ways; starting with reflection (note, this is slowish - OK for moderate amounts of data though):

var props = objectType.GetProperties(); foreach(object obj in data) {     foreach(var prop in props) {         object value = prop.GetValue(obj, null); // against prop.Name     } } 

However; for larger volumes of data it would be worth making this more efficient; for example here I use the Expression API 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):

static void Main() {             var data = new[] {        new { Foo = 123, Bar = "abc" },        new { Foo = 456, Bar = "def" },        new { Foo = 789, Bar = "ghi" },     };     string s = Write(data);         } static Expression StringBuilderAppend(Expression instance, Expression arg) {     var method = typeof(StringBuilder).GetMethod("Append", new Type[] { arg.Type });     return Expression.Call(instance, method, arg); } static string Write<T>(IEnumerable<T> data) {     var props = typeof(T).GetProperties();     var sb = Expression.Parameter(typeof(StringBuilder));     var obj = Expression.Parameter(typeof(T));     Expression body = sb;     foreach(var prop in props) {                     body = StringBuilderAppend(body, Expression.Property(obj, prop));         body = StringBuilderAppend(body, Expression.Constant("="));         body = StringBuilderAppend(body, Expression.Constant(prop.Name));         body = StringBuilderAppend(body, Expression.Constant("; "));     }     body = Expression.Call(body, "AppendLine", Type.EmptyTypes);     var lambda = Expression.Lambda<Func<StringBuilder, T, StringBuilder>>(body, sb, obj);     var func = lambda.Compile();      var result = new StringBuilder();     foreach (T row in data)     {         func(result, row);     }     return result.ToString(); } 
like image 170
Marc Gravell Avatar answered Sep 28 '22 19:09

Marc Gravell