Search and filter in MVC3 Razor using Linq This code works fine, but I just don't like all the if else.  If I keep adding field to filter, it's going to get messy.

I am not using EF and cannot on this.

Controller code:

var books = bookRepository.GetDogs();    
if (!String.IsNullOrEmpty(searchString))
{

    if (!String.IsNullOrWhiteSpace(searchString) &amp;&amp; searchGender != String.Empty &amp;&amp; searchHand != String.Empty)
    {
        books = books.Where(b =&gt; b.Name.ToUpper().Contains(searchString.ToUpper())
                                 &amp;&amp; b.Gender == searchGender &amp;&amp; b.Handedness == searchHand);
    }
    else if (!String.IsNullOrWhiteSpace(searchGender) &amp;&amp; searchString == String.Empty &amp;&amp; searchHand == String.Empty)
    {
        books = books.Where(b =&gt; b.Gender == searchGender);
    }
    else if (String.IsNullOrWhiteSpace(searchGender) &amp;&amp; searchString != String.Empty &amp;&amp; searchHand == String.Empty)
    {
        books = books.Where(b =&gt; b.Name.ToUpper().Contains(searchString.ToUpper()));
    }
}

return View(books);


My view:

&lt;p&gt;Find by Name : @Html.TextBox("searchString", ViewBag.CurrentFilter as string)


@Html.DropDownList("searchGender", new SelectList(ViewBag.BookNames), "-- Select All --")
@Html.DropDownList("searchHand", new SelectList(ViewBag.HandNames), "---Select All--")
Just put if, not else if so you can have a cumulative multi criteria search, and one condition in every if.

So every condition is easy to read, and if more than one criteria is filled, they will cumulate fine.

if (!String.IsNullOrWhiteSpace(searchString))
   books = books.Where(b =&gt; b.Name.ToUpper().Contains(searchString.ToUpper());       

if (!String.IsNullOrWhiteSpace(searchGender))
   books = books.Where(b =&gt; b.Gender == searchGender);

if (String.IsNullOrWhiteSpace(searchHand))
   books = books.Where(b =&gt; b.Handedness == searchHand);