Last active
September 24, 2023 08:17
-
-
Save sandord/400553 to your computer and use it in GitHub Desktop.
Get property name from lambda expression
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
/// <summary> | |
/// Returns the name of the specified property of the specified type. | |
/// </summary> | |
/// <typeparam name="T"> | |
/// The type the property is a member of. | |
/// </typeparam> | |
/// <param name="property"> | |
/// The property. | |
/// </param> | |
/// <returns> | |
/// The property name. | |
/// </returns> | |
public static string GetPropertyName<T>(System.Linq.Expressions.Expression<Func<T, object>> property) | |
{ | |
System.Linq.Expressions.LambdaExpression lambda = (System.Linq.Expressions.LambdaExpression)property; | |
System.Linq.Expressions.MemberExpression memberExpression; | |
if (lambda.Body is System.Linq.Expressions.UnaryExpression) | |
{ | |
System.Linq.Expressions.UnaryExpression unaryExpression = (System.Linq.Expressions.UnaryExpression)(lambda.Body); | |
memberExpression = (System.Linq.Expressions.MemberExpression)(unaryExpression.Operand); | |
} | |
else | |
{ | |
memberExpression = (System.Linq.Expressions.MemberExpression)(lambda.Body); | |
} | |
return ((PropertyInfo)memberExpression.Member).Name; | |
} |
Exactly what I was searching for!
Thanks
What about a property path (Example: Object.Property.OtherProperty.DesiredProperty)?
@sandord Awesome, thanks!
Thanks
Awesome, thanks a lot!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Awesome! Thank you!