Enumerating through an object's properties (string) in C#

Viewed 37332

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 it have to be hard coded?

Is there maybe a LINQ way to query an object's properties of type 'string' and to output them?

Do you have to hard code the property names you want to echo?

4 Answers

You can get all the properties of a type by using the GetProperties method. You can then filter this list using the LINQ Where extension method. Finally you can project the properties using the LINQ Select extension method or a convenient shortcut like ToDictionary.

If you want to limit the enumeration to properties having of type String you can use this code:

IDictionary<String, String> dictionary = myObject.GetType()
  .GetProperties()
  .Where(p => p.CanRead && p.PropertyType == typeof(String))
  .ToDictionary(p => p.Name, p => (String) p.GetValue(myObject, null));

This will create a dictionary that maps property names to property values. As the property type is limited to String it is safe to cast the property value to String and the type of the returned type is IDictionary<String, String>.

If you instead want all properties you can do it like this:

IDictionary<String, Object> dictionary = myObject.GetType()
  .GetProperties()
  .Where(p => p.CanRead)
  .ToDictionary(p => p.Name, p => p.GetValue(myObject, null));
Related