1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| Func<TonType> filtre = GetFilter<TonType>(c.Name, strToSearch);
mainDGV.DataSource = maList.FindAll(filtre);
...
private Expression<Func<T, bool>> GetFilter<T>(string propertyName, string strToSearch)
{
PropertyInfo prop = typeof(T).GetProperty(propertyName);
if (prop != null)
{
// On construit une expression pour implémenter le filtre :
// Paramètre de l'expression
ParameterExpression param = Expression.Parameter(typeof(T), "p");
// Accès à la propriété
Expression value = Expression.Property(param, prop); // p.<property>
// Si le type de la propriété est un type référence ou un type nullable (Nullable<T>), on va utiliser l'opérateur ??
if (!prop.PropertyType.IsValueType ||
prop.PropertyType.IsValueType && prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
Expression emptyString =
Expression.Convert(
Expression.Field(null, typeof(string).GetField("Empty")),
typeof(object));
value = Expression.Coalesce( // p.<property> ?? String.Empty
value, // p.<property>
emptyString); // String.Empty
}
// Si la propriété n'est pas de type String, on appelle ToString :
if (prop.PropertyType == typeof(string))
{
value = Expression.Convert(value, typeof(string));
}
else
{
value = Expression.Call(value, "ToString", new Type[] {});
}
// Appel de la méthode Contains
Expression contains =
Expression.Call(
value,
"Contains",
new Type[] {},
Expression.Constant(strToSearch));
// Expression finale
return Expression.Lambda<Func<T, bool>>(contains, param);
}
else
{
// La propriété n'existe pas, on renvoie un filtre qui laisse tout passer :
return item => true;
}
} |
Partager