| | 1 | | using System; |
| | 2 | | using System.Collections.Generic; |
| | 3 | | using System.Linq.Expressions; |
| | 4 | |
|
| | 5 | | namespace Plainquire.Sort; |
| | 6 | |
|
| | 7 | | /// <summary> |
| | 8 | | /// Extension methods for <see cref="Expression"/>. |
| | 9 | | /// </summary> |
| | 10 | | internal static class ExpressionExtensions |
| | 11 | | { |
| | 12 | | /// <summary> |
| | 13 | | /// Gets the path to a property (e.g. person.Address.Street). |
| | 14 | | /// </summary> |
| | 15 | | /// <typeparam name="TEntity">The entity that declares <typeparamref name="TProperty"/>.</typeparam> |
| | 16 | | /// <typeparam name="TProperty">The type of the property.</typeparam> |
| | 17 | | /// <param name="property">The property to get the access path to.</param> |
| | 18 | | /// <exception cref="ArgumentException"></exception> |
| | 19 | | public static string GetPropertyPath<TEntity, TProperty>(this Expression<Func<TEntity, TProperty>> property) |
| | 20 | | { |
| 158 | 21 | | var body = property.UnboxBody(); |
| | 22 | |
|
| 158 | 23 | | if (body is ParameterExpression) |
| 1 | 24 | | return PropertySort.PATH_TO_SELF; |
| | 25 | |
|
| 157 | 26 | | if (body is not MemberExpression currentProperty) |
| 1 | 27 | | throw new ArgumentException("Given property must be a chain of property access expressions like person => pe |
| | 28 | |
|
| 156 | 29 | | var properties = new List<string>(); |
| 205 | 30 | | while (currentProperty is { Expression: MemberExpression } memberAccessExpression) |
| | 31 | | { |
| 49 | 32 | | properties.Add(memberAccessExpression.Member.Name); |
| 49 | 33 | | currentProperty = (MemberExpression)memberAccessExpression.Expression; |
| 49 | 34 | | } |
| | 35 | |
|
| 156 | 36 | | if (currentProperty is not { Expression: ParameterExpression } parameterExpression) |
| 1 | 37 | | throw new ArgumentException("Given property must be a chain of property access expressions like person => pe |
| | 38 | |
|
| 155 | 39 | | properties.Add(parameterExpression.Member.Name); |
| | 40 | |
|
| 155 | 41 | | properties.Reverse(); |
| 155 | 42 | | return string.Join('.', properties); |
| | 43 | | } |
| | 44 | |
|
| | 45 | | private static Expression UnboxBody<TEntity, TProperty>(this Expression<Func<TEntity, TProperty>> property) |
| | 46 | | { |
| 158 | 47 | | if (property.Body is UnaryExpression { NodeType: ExpressionType.Convert } convert) |
| 24 | 48 | | return convert.Operand; |
| 134 | 49 | | return property.Body; |
| | 50 | | } |
| | 51 | | } |