Pregunta

Tengo un IQueryable y un objeto de tipo T.

Quiero hacer IQueryable (). Donde (o = > o.GetProperty (fieldName) == objectOfTypeT.GetProperty (fieldName))

entonces ...

public IQueryable<T> DoWork<T>(string fieldName)
        where T : EntityObject
{
   ...
   T objectOfTypeT = ...;
   ....
   return SomeIQueryable<T>().Where(o => o.GetProperty(fieldName) == objectOfTypeT.GetProperty(fieldName));
}

Fyi, GetProperty no es una función válida. Necesito algo que realice esta función.

¿Me estoy derritiendo el cerebro un viernes por la tarde o es algo complejo?


objectOfTypeT puedo hacer lo siguiente ...

var matchToValue = Expression.Lambda(ParameterExpression
.Property(ParameterExpression.Constant(item), "CustomerKey"))
.Compile().DynamicInvoke();

Lo que funciona perfectamente, ahora solo necesito la segunda parte:

devuelve SomeIQueryable (). Where (o = > o.GetProperty (fieldName) == matchValue);

¿Fue útil?

Solución

Me gusta así:

    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);

He iniciado un blog que cubrirá una serie de temas de expresiones, aquí .

Si tiene algún problema, otra opción es extraer el valor de objectOfTypeT primero (usando la reflexión) y luego usar ese valor en el Expression.Constant , pero sospecha que estará bien " como está " ;.

Otros consejos

Por lo que puedo ver hasta ahora, tendrá que ser algo así como ...

IQueryable<T>().Where(t => 
MemberExpression.Property(MemberExpression.Constant(t), fieldName) == 
ParameterExpression.Property(ParameterExpression.Constant(item), fieldName));

Aunque puedo hacer que esto se compile, no se está ejecutando de la forma necesaria.

¿Qué pasa con:

    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);
    }

Esta es una forma de obtener valores de una propiedad por cadena sin utilizar consultas dinámicas. La desventaja es que todos los valores serán en caja o sin caja.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top