I've been playing a bit with (d)Linq lately so there are probably some related blog posts coming this way :).
Today, for example, I was trying to get the logic for a search form to work. The form is pretty basic, allowing the user to search a books library based on several fields, like Title, Author, Publisher etc. The search should tokenize the input from each field and then build the final condition by OR-ing the conditions for each field together, provided that something was entered in that search field to start with. For example one could search for Title containing "patterns design" OR Author containing "Gamma". Should be simple with (d)Linq, right? Almost... :)
If I wanted to do a similar search to the one described above, but instead of OR-ing the conditions, AND-ing them (ie Title contains "patterns" AND Author contains "Gamma") this is pretty straightforward, along the lines of maybe (no tokenizing):
IQueryable<Book> query = from b in db.Books select b;
if (!string.IsNullOrEmpty(title))
{
query = from b in query
where b.Title.Contains(title)
select b;
}
if (!string.IsNullOrEmpty(author))
{
query = from b in query
where b.Author.Contains(author)
select b;
}
… and so on
So what about OR-ing? Well, to be honest I thought of a bad solution :), but then found a little utility class by Joe Albahari (scroll down to the last posts on that page), which does some magic and gets stuff to work. VERY cool and neat!
Also, if you happen to know of another way to do this, please share...