Home > OS >  C# Linq Replace Not Filtering Correctly in Jquery Datatable
C# Linq Replace Not Filtering Correctly in Jquery Datatable

Time:01-05

The following is supposed to work as so:

  1. User enters value "Apartment 101" in the "Apartment/Space/Other" search field.
  2. The "Apartment" part of the value is replaced by an empty string ("").
  3. Records with values that include "101" are displayed in the search results. This can include "Space 101", "Num 101", "Apartment 101", etc.

Currently, if I enter "Apartment 101", the search results include only records with "Apartment 101".

    var apartment = Request.Form.GetValues("columns[1][search][value]")[0];

    if (!string.IsNullOrWhiteSpace(apartment))
    {
        if (apartment.Contains("Num"))
            apartment.Replace("Num", "");
        if (apartment.Contains("Apartment"))
            apartment.Replace("Apartment", "");
        if (apartment.Contains("Space"))
            apartment.Replace("Space", "");

        data = data.Where(gsn => gsn.Apartment.Contains(apartment));
    }

I tried using the Contains function to see if a certain string is in the value entered. If it is, then I tried using the Replace function to replace that value with an empty string ("").

When I search for a value, such as "Space 301", I expect to see all records with "301" in the search results.

CodePudding user response:

string.replace returns the value and does not change the main variable so change it to something like this:

if (!string.IsNullOrWhiteSpace(apartment))
    {
        if (apartment.Contains("Num")){
            apartment = apartment.Replace("Num", "");
            data = data.Where(gsn => gsn.Num.Contains(apartment));
        }else
        if (apartment.Contains("Apartment")){
            apartment = apartment.Replace("Apartment", "");
            data = data.Where(gsn => gsn.Apartment.Contains(apartment));
         }else
        if (apartment.Contains("Space")){
            apartment = apartment.Replace("Space", "");
            data = data.Where(gsn => gsn.Space.Contains(apartment));
        }

        
    }
  • Related