0

In the UI, there's a dropdown that takes value for parameter 'field'. It can be a specific value or 'All' is the default where all rows irrespective of 'field' value needs to be retrieved.

How do I write the Where clause in LINQ such that if user supplies a value for field column, then use it as filter otherwise grab all rows from DB?

1 Answer 1

2

You can use IQueryable<T> as a base for your LINQ query and append to it all you need:

Example:

        string userInput = "";
        using (var context = new EntityModel())
        {
            IQueryable<MyEntity> query = context.MyEntities;

            if (!String.IsNullOrWhiteSpace(userInput))
                query = query.Where(x => x.MyFilterableProperty == userInput);

            return query.ToList();
        }
Sign up to request clarification or add additional context in comments.

6 Comments

Why remove the ToList()? Its purely an example and it causes the execution of the query.
Because the entire point of your answer is to use IQueryable<T> and with ToList that dissapears...
The ToList() is my way of stating it is the end of the example because the query is being executed. The example is whole as in depending on whether userInput is set or not, the query differs.
Never mind - it is a detail. Gave you a +1... I think in L2S you should defer query execution as long as you can.
@Jeffery Khan Thanks! However, I am having difficulty converting my code to this IQueryable format. I have a select query such as var result = <my select query>. How do I make it IQueryable. Sorry I am new to L2S and thanks again for helping.
|

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.