Let\'s say I have many objects and they have many string properties.
Is there a programatic way to go through them and output the propertyname and its value or does
Use reflection. It's nowhere near as fast as hardcoded property access, but it does what you want.
The following query generates an anonymous type with Name and Value properties for each string-typed property in the object 'myObject':
var stringPropertyNamesAndValues = myObject.GetType()
.GetProperties()
.Where(pi => pi.PropertyType == typeof(string) && pi.GetGetMethod() != null)
.Select(pi => new
{
Name = pi.Name,
Value = pi.GetGetMethod().Invoke(myObject, null)
});
Usage:
foreach (var pair in stringPropertyNamesAndValues)
{
Console.WriteLine("Name: {0}", pair.Name);
Console.WriteLine("Value: {0}", pair.Value);
}