Last active
December 17, 2016 11:40
-
-
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"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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