making a search for my site without having to nestle multiple IFS
I would like to search my database for products开发者_C百科 from a table(products) The problem is i do not want 600 rows of code with multiple if's. The code looks as following atm(do not want it like this)
Public Function GetSearchResults(ByVal County As Integer, Optional ByVal Searchtext As String = "", Optional ByVal Category As Integer = 0, Optional ByVal SubCategory As Integer = 0) As List(Of Product)
Dim dc As New DataClassesDataContext
Dim Listholder As New List(Of Product)
If Searchtext IsNot "" Then
If County > 0 Then
If Category > 0 Then
If SubCategory = 0 Then
Dim Results = From p In dc.Products _
Where p.Headline.Contains(Searchtext) _
Where p.CategoryID = Category _
Where p.CountyID = County _
Select p
Listholder = Results.ToList
Return Listholder.ToList
AND alot of elseifs and so on... The problem is that if the value is 0 at any of the above the search will be for all countys/categorys/headlines.... is there a better way to do this? i mean linq is great there have to be a way to make it more dynamic so i dont need the IFS.
You could just chain your Where filters.
public static void Search(String headline = null, Int32 county = 0, Int32 category = 0, Int32 subCategory = 0) {
var dc = new DataClassesDataContext();
var result = dc.Products;
if (headline != null)
result = result.Where(p => p.Headline.Contains(headline));
if (county != 0)
result = result.Where(p => p.CountyId == county);
if (category != 0)
result = result.Where(p => p.CategoryId == category);
if (subCategory != 0)
result = result.Where(p => p.SubCategoryId == subCategory);
var listHolder = result.ToList();
// ...
}
Instead of nesting if
s, invert them and return
:
if value is "" then Exit Function
if County <= 0 then Exit Function
Notice how the condition suddenly becomes positive, too.
[EDIT]
Split the 600 lines into smaller functions where each of them just does one search. Use the code above to leave them early if searching doesn't make sense in this case. Then use a new "main" function to invoke them until one of them returns a result (or similar). In an OO language, I'd create "workers", run each until one of them told me "I got it".
Not sure I'm entirely understanding your question - you want to search on a value when it's non zero, but return all rows when it's 0? You could roll that comparison up into the Where's
Where (CategoryID > 0 AND p.CategoryID = Category) OR (CategoryID = 0) _
Where (CountyID > 0 AND p.CountyID = CountyID) OR (CountyID = 0) _
Where (SubCategoryID > 0 AND p.SubCategoryID = SubCategoryID) or (SubCategoryID = 0)
I don't know VB, but could you not submit a list of required search items and create a dynamic database query?
精彩评论