Here are some extension methods to get the values of properties, supporting navigation of properties. For example:
- customer.GetValueForPath(“Name”)
- order.GetValueForPath(“Customer.Name”)
This might come in handy once in a while. (I used it to export the data displayed in a Datagrid)
- ///<summary>
- /// Gets the value for path.
- ///</summary>
- ///<param name=”obj”>The object to get the value from.</param>
- ///<param name=”path”>The path of the property to get (Path of property names).</param>
- public static object GetValueForPath(this object obj, string path)
- {
- if (obj == null) return null;
- var type = obj.GetType();
- var propertyPath = type.GetPropertyPath(path);
- return propertyPath == null ? null : obj.GetValueForPath(propertyPath);
- }
- ///<summary>
- /// Gets the value for path.
- ///</summary>
- ///<param name=”obj”>The object to get the value from.</param>
- ///<param name=”path”>The path of the property to get (Path of PropertyInfo’s).</param>
- ///<returns></returns>
- public static object GetValueForPath(this object obj, IEnumerable<PropertyInfo> path)
- {
- object result = obj;
- foreach (var info in path)
- {
- if (result == null) break;
- result = info.GetValue(result, null);
- }
- return result;
- }
- ///<summary>
- /// Translates a string property path, to a list of PropertyInfo objects
- ///</summary>
- ///<param name=”type”>The type of the base object.</param>
- ///<param name=”path”>The path to get the PropertyInfo’s for.</param>
- ///<returns></returns>
- public static IList<PropertyInfo> GetPropertyPath(this Type type, string path)
- {
- var propertyPath = new List<PropertyInfo>();
- if (!string.IsNullOrEmpty(path))
- {
- var propertyNames = path.Split(‘.’);
- var currentType = type;
- foreach (var propertyName in propertyNames)
- {
- var prop = currentType.GetProperty(propertyName);
- if (prop == null)
- {
- Debug.WriteLine(“TypeExtensions.GetPropertyPath Error: Property ‘{0}‘ does not exist on type ‘{1}‘. In path ‘{2}‘ on type ‘{3}‘”, propertyName, currentType.Name, path, type.Name);
- break;
- }
- propertyPath.Add(prop);
- currentType = prop.PropertyType;
- }
- }
- return propertyPath;
- }