Created
January 30, 2022 14:56
-
-
Save alfeg/b15c1958bb45a9bd65591cdd952ead89 to your computer and use it in GitHub Desktop.
Get object property by path with nesting
This file contains hidden or 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
Func<T, object?>? CreateDelegate(string path) | |
{ | |
var type = typeof(T); | |
var param = Expression.Parameter(type); | |
var parts = path.Split('.'); | |
var prop = Expression.Property(param, parts[0]); | |
foreach (var part in parts.Skip(1)) | |
{ | |
prop = Expression.Property(prop, part); | |
} | |
var lamba = Expression.Lambda(prop, param).Compile(); | |
var invoker = lamba.GetType().GetRuntimeMethod("Invoke", new[] { type }); | |
return invoker == null ? o => null : o => invoker.Invoke(lamba, new object?[] { o }); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment