How to use the value from a property accessor LINQ expression in a Contains LINQ expression?

StackOverflow https://stackoverflow.com/questions/16173740

  •  11-04-2022
  •  | 
  •  

Question

I currently have a LINQ expression for a property accessor that accesses a property on an object. I now need to build a LINQ expression that will evaluate a predicate to see if the result from the property accessor is contained within a list.

I've seen that in most cases this kind of thing is done using the static methods on Expression, however there is no Contains or In available as a static method on Expression, so I am unsure how to proceed.

// A data object
internal class PersonDAL
{
    public int Age ( get; set; }
}

// A business object
public class Person
{
    private PersonDAL root { get; set; }

    public static Expression<Func<PersonDAL, int>> AgeExpression
    {
        get
        {
            return (root) => (root.Age);
        }
    }
}

Now I want to be able to check if the value of AgeExpression is contained within a list of ages. Normally this would be something like writing an expression to see if the list of values contains the value that I want to check for, but I don't see how to feed the result of an expression in as the value to search for.

To clarify a little, I'm trying to figure out how to take a queryable that has all Persons and get just the Persons where an unknown expression evaluates true based on a value from another expression. In my sample case, the unknown accessor expression is looking at the Age of a Person and it needs to be able to evaluate if it is contained within another list of acceptable ages.

Était-ce utile?

La solution

I'm not sure why you're using expressions. I don't see what you gain by them. But if you modify the signature of AgeExpression to be Expression<Func<PersonDAL, int>>, you can compile it and execute it:

void Main()
{
    var pDal = new PersonDAL { Age = 3 };

    var ageFunc = Person.AgeExpression.Compile();
    var age = ageFunc(pDal);
    // age is 3
}

// Define other methods and classes here

// A data object
public class PersonDAL
{
    public int Age { get; set; }
}

// A business object
public class Person
{
    public Person(PersonDAL dal)
    {
        this.dal = dal;
    }

    private PersonDAL dal { get; set; }

    public static Expression<Func<PersonDAL, int>> AgeExpression
    {
        get
        {
            return (root) => (root.Age);
        }
    }
}

Autres conseils

This kind of problem foxed me a lot too.. remember that you can access local variables within your LINQ/lambda expressions: so a simple .where(x => x.value == AgeExpression) should point you in the right direction

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top