Aqua267
Aqua267

Reputation: 953

LINQ to SQL: where clause filter based on user input

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?

Upvotes: 0

Views: 466

Answers (1)

Khan
Khan

Reputation: 18142

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

Upvotes: 2

Related Questions