Skip to content

Instantly share code, notes, and snippets.

@angularsen
Last active December 17, 2016 11:40
Show Gist options
  • Save angularsen/862c1cd9983d7525d2ddee0bb2706c3a to your computer and use it in GitHub Desktop.
Save angularsen/862c1cd9983d7525d2ddee0bb2706c3a to your computer and use it in GitHub Desktop.
Helper class for converting property expression x => x.Foo.Bar to property path string "Foo.Bar"
/// <remarks>Inspired by: http://stackoverflow.com/a/22135756/134761 </remarks>
public static class PropertyPath<TSource>
{
public static string GetString(Expression<Func<TSource, object>> expression, string separator = ".")
{
return string.Join(separator, GetPropertyPathSegments(expression));
}
public static IReadOnlyList<string> GetPropertyPathSegments(Expression<Func<TSource, object>> expression)
{
var visitor = new PathVisitor();
visitor.Visit(expression.Body);
if (!visitor.Path.All(x => x is PropertyInfo))
{
throw new ArgumentException("The path can only contain properties", nameof(expression));
}
return visitor.Path.Select(x => x.Name)
.Reverse()
.ToArray();
}
private class PathVisitor : ExpressionVisitor
{
internal readonly List<MemberInfo> Path = new List<MemberInfo>();
protected override Expression VisitMember(MemberExpression node)
{
Path.Add(node.Member);
return base.VisitMember(node);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment