Come faccio a creare un albero delle espressioni Linq confrontandolo con un oggetto generico?
-
04-07-2019 - |
Domanda
Ho un IQueryable e un oggetto di tipo T.
Voglio fare IQueryable (). Where (o = > o.GetProperty (fieldName) == objectOfTypeT.GetProperty (fieldName))
quindi ...
public IQueryable<T> DoWork<T>(string fieldName)
where T : EntityObject
{
...
T objectOfTypeT = ...;
....
return SomeIQueryable<T>().Where(o => o.GetProperty(fieldName) == objectOfTypeT.GetProperty(fieldName));
}
Cordiali saluti, GetProperty non è una funzione valida. Ho bisogno di qualcosa che svolga questa funzione.
Sto avendo uno scioglimento del cervello del venerdì pomeriggio o è una cosa complessa da fare?
objectOfTypeT Posso fare quanto segue ...
var matchToValue = Expression.Lambda(ParameterExpression
.Property(ParameterExpression.Constant(item), "CustomerKey"))
.Compile().DynamicInvoke();
Che funziona perfettamente, ora ho solo bisogno della seconda parte:
restituisce SomeIQueryable (). Where (o = > o.GetProperty (fieldName) == matchValue);
Soluzione
In questo modo:
var param = Expression.Parameter(typeof(T), "o");
var fixedItem = Expression.Constant(objectOfTypeT, typeof(T));
var body = Expression.Equal(
Expression.PropertyOrField(param, fieldName),
Expression.PropertyOrField(fixedItem, fieldName));
var lambda = Expression.Lambda<Func<T,bool>>(body,param);
return source.Where(lambda);
Ho aperto un blog che tratterà una serie di argomenti relativi alle espressioni, qui .
In caso di problemi, un'altra opzione è estrarre prima il valore da objectOfTypeT
(usando reflection) e quindi utilizzare quel valore in Expression.Constant
, ma io sospetto che andrà bene " come è " ;.
Altri suggerimenti
Da quello che posso vedere finora dovrà essere qualcosa di simile ...
IQueryable<T>().Where(t =>
MemberExpression.Property(MemberExpression.Constant(t), fieldName) ==
ParameterExpression.Property(ParameterExpression.Constant(item), fieldName));
Anche se riesco a farlo compilare, non sta eseguendo esattamente come richiesto.
Che dire di:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public Func<T, TRes> GetPropertyFunc<T, TRes>(string propertyName)
{
// get the propertyinfo of that property.
PropertyInfo propInfo = typeof(T).GetProperty(propertyName);
// reference the propertyinfo to get the value directly.
return (obj) => { return (TRes)propInfo.GetValue(obj, null); };
}
public void Run()
{
List<Person> personList = new List<Person>();
// fill with some data
personList.Add(new Person { Name = "John", Age = 45 });
personList.Add(new Person { Name = "Michael", Age = 31 });
personList.Add(new Person { Name = "Rose", Age = 63 });
// create a lookup functions (should be executed ones)
Func<Person, string> GetNameValue = GetPropertyFunc<Person, string>("Name");
Func<Person, int> GetAgeValue = GetPropertyFunc<Person, int>("Age");
// filter the list on name
IEnumerable<Person> filteredOnName = personList.Where(item => GetNameValue(item) == "Michael");
// filter the list on age > 35
IEnumerable<Person> filteredOnAge = personList.Where(item => GetAgeValue(item) > 35);
}
Questo è un modo per ottenere i valori di una proprietà per stringa senza usare query dinamiche. Il rovescio della medaglia è che tutti i valori saranno boxed / unboxed.