Guest User

Untitled

a guest
Feb 21st, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  1. public static partial class TypeExtensions
  2. {
  3. public static MemberExpression GetNestedFieldExpression(this Type me, string address, Expression parent = null)
  4. {
  5. var myExpression = parent ?? Expression.Constant(Activator.CreateInstance(me));
  6.  
  7. if (address.Contains('.'))
  8. {
  9. var nestedAddress = address.Split(new char[] { '.' }, 2);
  10.  
  11. var nestedProp = me.GetProperty(nestedAddress[0]);
  12. if (nestedProp == null) return null;
  13.  
  14. // if we're trying to express through IEnums then we need
  15. // to call FirstOrDefault() so that it can access the type
  16. // contained within itself
  17. Type nestedType = nestedProp.PropertyType;
  18. Expression nestedExpression = Expression.Property(myExpression, nestedAddress[0]);
  19. if (
  20. nestedType.IsGenericType &&
  21. (
  22. nestedType.GetGenericTypeDefinition() == typeof(IEnumerable<>) ||
  23. nestedType.GetGenericTypeDefinition() == typeof(List<>)
  24. )
  25. )
  26. {
  27. nestedType = nestedType.GetGenericArguments()[0];
  28. nestedExpression = Expression.Call(typeof(Enumerable), "FirstOrDefault", new Type[] { nestedType }, nestedExpression);
  29. }
  30.  
  31. return nestedType.GetNestedFieldExpression(
  32. nestedAddress[1],
  33. nestedExpression
  34. );
  35. }
  36. else
  37. {
  38. var nestedProp = me.GetProperty(address);
  39. if (nestedProp == null) return null;
  40.  
  41. return Expression.Property(myExpression, address);
  42. }
  43. }
  44. }
Add Comment
Please, Sign In to add comment