Created
January 16, 2014 20:53
-
-
Save joshgo/8463206 to your computer and use it in GitHub Desktop.
C# Linq Expressions that cache's the get properties
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
| private static Dictionary<Type, Dictionary<string, object>> _propertyAccess = new Dictionary<Type, Dictionary<string, object>>(); | |
| private static void CacheProperties<T>() | |
| { | |
| if (_propertyAccess.ContainsKey(typeof(T))) | |
| return; | |
| _propertyAccess.Add(typeof(T), new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase)); | |
| foreach (var prop in typeof(T).GetProperties()) | |
| { | |
| var xtype = System.Linq.Expressions.Expression.Parameter(typeof(T)); | |
| var xprop = System.Linq.Expressions.Expression.Property(xtype, prop.Name); | |
| var xconv = System.Linq.Expressions.Expression.Convert(xprop, typeof(object)); | |
| var exp = System.Linq.Expressions.Expression.Lambda(xconv, xtype); | |
| var func = exp.Compile(); | |
| _propertyAccess[typeof(T)][prop.Name] = func; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment