Skip to content

Instantly share code, notes, and snippets.

@joshgo
Created January 16, 2014 20:53
Show Gist options
  • Save joshgo/8463206 to your computer and use it in GitHub Desktop.
Save joshgo/8463206 to your computer and use it in GitHub Desktop.
C# Linq Expressions that cache's the get properties
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