osyris zosar

osyris zosar

  • NA
  • 289
  • 26.9k

Trying to filter Database Data based on ID

Mar 5 2021 5:31 AM
Hello I am Trying to Filter Database Data base on ID but i cant get it to work;
 
Code:
  1. public async Task<ActionResult> Index(string searchString, string description)  
  2.       {  
  3.           var AllProducts =  from m in _context.Products  
  4.                                         select m;  
  5.   
  6.           List<int> IDList = new List<int>();  
  7.           IDList.Clear();  
  8.   
  9.           int count = 0;  
  10.   
  11. filter base on Title  
  12.   
  13.           if (!String.IsNullOrEmpty(searchString))  
  14.           {  
  15.               count++;  
  16.               var FilterSearch = from Products in AllProducts  
  17.                                   where Products.Title.Contains(searchString)  
  18.                                   select Products.Id;  
  19.   
  20.               foreach (int Product in FilterSearch)  
  21.                   IDList.Add(Product);  
  22.           }  
  23.   
  24.  filter based on description  
  25.   
  26.           if (!String.IsNullOrEmpty(description))  
  27.           {   
  28.               count++;  
  29.               var FilterDesc = from Products in AllProducts  
  30.                               where Products.ProductDescription.Contains(description)  
  31.                               select Products.Id;  
  32.   
  33.               foreach (int Products in FilterDesc)  
  34.                   IDList.Add(Products);  
  35.           }  
  36.            
  37.  making sure that only data that have ID simulair appear  
  38.   
  39.           if (IDList.Count != 0)  
  40.           {  
  41.               var filter2 = IDList.GroupBy(x => x)  
  42.                              .Where(g => g.Count() == count)  
  43.                              .Select(y => y.Key)  
  44.                              .ToList();  
  45.   
  46.              //under this line is what I think the problem  
  47.               AllProducts = AllProducts.Where(x => x.Id.Equals(filter2));  
  48.            
  49.           }  
  50.               return View(await AllProducts.ToListAsync());  
  51.             
  52.       }  
 
everything works except for this code on line 47:
  1. AllProducts = AllProducts.Where(x => x.Id.Equals(filter2));    
when I type something in both search fields (description and searchStrings)
It return back nothing
 
Only when both search fields are empty they show all the data
 I just need the Data Database that have simulair ID's as those of the numbers in  filter2 list
 
How do i manage that? 

Answers (2)