Consider the following code:
string propertyName;
var dateList = new List() { DateTime.Now };
propertyName = dateList.GetPropertyName(dateTimeObj
This is the version I use, it returns a PropertyInfo
, but getting the name is trivial.
public static PropertyInfo GetProperty<T>(Expression<Func<T, object>> expression)
{
MemberExpression memberExpression = null;
if (expression.Body.NodeType == ExpressionType.Convert)
{
memberExpression = ((UnaryExpression) expression.Body).Operand as MemberExpression;
}
else if (expression.Body.NodeType == ExpressionType.MemberAccess)
{
memberExpression = expression.Body as MemberExpression;
}
if (memberExpression == null)
{
throw new ArgumentException("Not a member access", "expression");
}
return memberExpression.Member as PropertyInfo;
}
Something like this should do the trick:
public static string GetPropertyName<T>(this IList<T> list, Expression<Func<T, object>> expr) {
MemberExpression member_expression = expr.Body as MemberExpression;
if (member_expression == null)
throw new ArgumentNullException("member_expression");
MemberInfo member = member_expression.Member;
PropertyInfo property = member as PropertyInfo;
string proname = memeber.name;
}
WARNING: Air Code!
here is a very easy and fast way to do it on this blog: http://blog.bittercoder.com/PermaLink,guid,206e64d1-29ae-4362-874b-83f5b103727f.aspx
So given:
Func func = Name => "Value";
You can get the lambda parameter "Name" from the function delegate by calling:
func.Method.GetParameters()[0].Name (would return "Name")
Here's the revised Hash method from Andrey:
public Dictionary<string, T> Hash<T>(params Func<string, T>[] args)
where T : class
{
var items = new Dictionary<string, T>();
foreach (var func in args)
{
var item = func(null);
items.Add(func.Method.GetParameters()[0].Name, item);
}
return items;
}
Hope it helps, Patrick
Just a side note: func.Method.GetParameters()[0].Name is extremelly fast when compared with compiling the lambda and extracting the member expression, then the member info, then the name.