C#: How to get the nested property value from a lambda expression

If you have a method that takes in a lambda expression as follows:

Column(x => x.Product.Category.Name);

then the following helper method will retrieve the value from the given property/expression:

public static object GetPropertyValueFromExpression<T, TProp>(object item, Expression<Func<T, TProp>> expression)
{
	var propertyPath = expression.Body.ToString().Replace(expression.Parameters[0] + ".", string.Empty);

	foreach (var part in propertyPath.Split('.'))
	{
		if (item == null)
			return null;

		var type = item.GetType();

		var property = type.GetProperty(part);
		if (property == null)
			return null;

		item = GetPropertyValue(item, property);
	}

	return item;
}
Published: 21.08.2011
  • Tags:
  • C#

blog comments powered by Disqus