1

First, I have a variable like below:

List<string> values;

Now I need build query condition like below:

Expression<Func<docinstance, bool>> filter = d=>d.values.any(o=>o.value==values[0]||o.value==value[1]||.....)

Because I don't know how many items in variable values, so how can I build the query condition

3 Answers 3

5

You can use Any again inside

d => d.values.Any(o => values.Any(x => x == o.value))
Sign up to request clarification or add additional context in comments.

3 Comments

This generates a double EXIST and 2(n-1) UNIONs of single row tables. Contains is much better (1 IN clause).
@GertArnold - In what ways is it better? Is execution faster? Is the Query Execution Plan different?
Contains has scalability problems, but Any is not scalable at all. When values has relatively many elements (~50) the query will throw an exception "nested too deeply".
1

You can use Contains:

d => d.values.Any(o => values.Contains(o.value))

See Documentation

Comments

0

The DbContext class of EF has a method Set<TEntity>() which return type is DbSet<TEntity> which implements Queryable interface which has all the query methods as extension methods.

At the end your query expression in translated into SQL and then executed. Which gives you the desired capability so that you can combine query methods and construct dynamic expressions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.