I have a method that works OK to get the index of a list using a class property as argument.
The code:
public static int GetIndex<T, TKey>(this T myTypeClass, Expression<Func<T, TKey>> propertySelector)
{
var body = (MemberExpression)propertySelector.Body;
var propertyInfo = (PropertyInfo)body.Member;
// list where I need to find the index for the property defined in the argument
List<KeyValuePair<PropertyInfo, int>> indexList = GlobalClassList;
// simple LINQ line to retrieve the int that corresponds with the 'propertyInfo'
int i = indexList.FindIndex(p => p.Key.Equals(propertyInfo));
return i;
}
To call the method:
MyClass myClass = new MyClass();
myClass.GetIndex(c=>c.property)
What I'm trying to do, is to simplify the argument in the method using just the property of the class (c.property
) instead having to rely on the use of the Expression<Func<T, TKey>>
(c=>c.property
). Is this possible?
Aucun commentaire:
Enregistrer un commentaire