9

I want to write a RavenDB query that filters by a value if it is available, but if that value is not available, I want it to return all objects. For example, in linq to objects, I can do something like this:

var matches = people.Where(x => x.LastName == userEntry || userEntry == string.Empty).ToList();

But the following will not work:

var matches = RavenSession.Query<Person>().Where(x => x.LastName == userEntry || userEntry == string.Empty).ToList();

Because userEntry is not an indexed value, this throws an exception.

How can I accomplish this?

egbrad
  • 2,387
  • 2
  • 23
  • 27
  • Worst case scenario, just do an if statement to check `userEntry == string.Empty` and query accordingly! Bonus, it's easier to understand!! – banging Jun 25 '12 at 19:13
  • I think I see what you mean, but I simplified the question for clarity. My actual scenario is more complicated, where I have ~10 fields that are all optional for filtering, and whichever ones the user fills in, I want to include those in the query. But if the user leaves them blank, they should be left out. So it would be impractical to write if statements with different queries for every possible combination of filters. – egbrad Jun 25 '12 at 19:16

1 Answers1

11

Based on your comment about multiple optional predicates, you should be able to do something like this:

var where = new List<Expression<Func<Person, bool>>>();

if (!string.IsNullOrWhitespace(lastName))
    where.Add(p => p.LastName == lastName);

if (!string.IsNullOrWhitespace(firstName))
    where.Add(p => p.FirstName == firstName);

// etc...

var query = session.Query<Person>();

foreach (var clause in where)
    query = query.Where(clause);

var results = query.ToList();
Jim Bolla
  • 8,265
  • 36
  • 54