search decimal values in Linq query

后端 未结 3 1150
独厮守ぢ
独厮守ぢ 2021-01-16 09:33

I have this search terms

[HttpPost]
public ActionResult Index(string searchString)
{
    if (!String.IsNullOrEmpty(searchString))
    {
        students = st         


        
3条回答
  •  北海茫月
    2021-01-16 09:56

    Though it is a old question posting answer so that other will do it correctly
    First thing to correct is we need to convert first integer to decimal and then search, assuming datatype for searchable column is also decimal

    So first convert your search string to decimal

                   decimal dec;
                   bool IsDecimal = decimal.TryParse(searchString, out dec);
    
                   // Truncating search to 2 digits this should be equal to your db            
                   // column precision so that rounding case are handled properly 
                   decimal TruncateDigits = -1;
                   if (IsDecimal)
                       TruncateDigits = Convert.ToDecimal(Math.Truncate(dec * 100) / 100); 
    

    Now your search filed is same as your db coloumn precison and ready to get searched

        students = students.Where(s => s.FIRST_NAME.Contains(searchString) 
                || s.LAST_NAME.Contains(searchString)
                || s.PERSONAL_NUMBER.Contains(searchString)
                || s.ACD_UNI_DEGREES.DEGREE.Contains(searchString)
                || s.ACD_UNI_FACULTIES.FACULTY.Contains(searchString)
                || s.ACD_UNI_SPECIALIZATIONS.SPECIALIZATION.Contains(searchString)
                || (IsDecimal && (decimal.Round(s.SEMESTER, 2) == TruncateDigits)) 
    

    Important point to note

          (IsDecimal && (decimal.Round(s.SEMESTER, 2) == TruncateDigits)) 
    

    Here again we will round to db column precision to handle rounding.

    Also SqlFunctions.StringConvert will do rounding internally so if your number is db is 68.88 and your are searching for 68 it wont search because StringConvert will give you 69 (rounding) so if you want to search for 68 then you need to use Floor function
    Something like

         SqlFunctions.StringConvert(decimal.Floor(s.SEMESTER)).Contains(searchString) 
    

    Hope this helps !!!

提交回复
热议问题