Kaizer
Kaizer

Reputation: 661

How to dynamically build up a query in linq

I want to dynamically build up my where clause for my linq query.

I have a search option which can search for name, sex and location. How can I dynamically build up my linq query so that if only name is entered I get something like:

profiles.where(function(x) x.name = <<nameValue>>)

but when the name is entered and the location I would get something like:

profiles.where(function(x) x.name = <<nameValue>> AND x.location = <<locationValue>>)

kind regards

Upvotes: 0

Views: 2910

Answers (2)

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

If your conditions are always ANDed, and never ORed you can build your query one step at the time:

Dim query = profiles.AsQueryable()

If Not String.IsNullOrEmpty(nameValue) Then
    query = query.Where(Function(x) x.name = nameValue)
End If

If Not String.IsNullOrEmpty(locationValue) Then
    query = query .Where(Function(x) x.location = locationValue)
End If

Return query.ToList()

LINQ queries execution is deferred so it's not executed until result are necessary or you explicitly ask it to execute, e.g. calling ToList() method.

Upvotes: 1

Thomas Levesque
Thomas Levesque

Reputation: 292405

You can use PredicateBuilder

Dim pred = PredicateBuilder.True(Of Profile)()
If Not String.IsNullOrEmpty(nameValue) Then
    pred = pred.And(Function(x) x.name = nameValue)
End If
If Not String.IsNullOrEmpty(locationValue) Then
    pred = pred.And(Function(x) x.location = locationValue)
End If

Dim query = profiles.Where(pred)

(Note: this solution assumes profiles is an IQueryable<Profile>, e.g. an Entity Framework DbSet or ObjectSet; if it's just a normal collection, use profiles.AsQueryable() instead of profiles)

Upvotes: 3

Related Questions