Search my site without resorting to multiple IFS

I would like to search my database for products from the table (products). The problem is that I do not want 600 lines of code with multiple ifs. The code is as follows: (I don't want this to be so)

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 a lot of elseifs etc. The problem is that if the value is 0 for any of the above, the search will be for all countys / categorys / headlines .... is there a better way to do this? I mean that linq is great, there should be a way to make it more dynamic, so I don't need IFS.

+3
source share
4 answers

You can simply bind 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();
    // ...
}
+3
source

Instead of nesting ifs, invert them and return:

if value is "" then Exit Function
if County <= 0 then Exit Function

, .

[EDIT]
600 , . , , . "" , , ( ). OO "", , " ".

+1

, - , , , 0? Where

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)
+1

VB, ?

0

Source: https://habr.com/ru/post/1783433/


All Articles