How to loop through properties of objects in c#? -
i have method gets values of properties of object , appends commas it. want make generinc can use other objects.
foreach (var row in rows.tolist()) { sbresult.append( delimiter + row.medianame + delimiter + separator + delimiter + row.countryname + delimiter + separator + delimiter + row.itemoverridedate + delimiter + separator + delimiter + row.rating + delimiter + separator + delimiter + row.batchno + delimiter + separator + delimiter + row.noinbatch + delimiter + separator + delimiter + row.batchdate + delimiter + separator + delimiter + row.datatype + delimiter + separator + delimiter + row.byline + delimiter + separator + delimiter + row.issueno + delimiter + separator + delimiter + row.issue + delimiter + separator + delimiter + row.messageno + delimiter + separator + delimiter + row.message + delimiter + separator + delimiter + row.sourcename + delimiter + separator + delimiter + row.sourcetype + delimiter + separator); //end of each row sbresult.appendline(); }
i have tried using var rowdata = row.gettype().getproperties();
returns property , dont know how value of property.
since type.getproperties
returns collection of propertyinfo
, follow calling propertyinfo.getvalue
. here's how can (and rest together) linq:
var line = string.join( row.gettype().getproperties() .select(pi => pi.getvalue(row)) .select(v => delimiter + v.tostring() + delimiter), separator);
however, might want reconsider approach. code break if getproperties
fetches static properties or indexers along "normal" properties; requires code run full trust (otherwise no reflection possible). , finally, it's going slow because a) reflection inherently slow , b) keep reflecting on same things on , on again without caching of information has discovered.
in addition above potential problems, if there remote chance later want filter gets printed out better encapsulate logic inside (virtual
?) method on row
, like
sbresult.appendline(row.serializeasline());