IQueryable Multiple filters on same item

osyris 236 Reputation points
2022-07-25T19:25:07.293+00:00

I am working on a hotel website
the website has 5 Check buttons ranging from 1 Hotel Star to 5

if none of the checkbuttons are enabled/clicked it should show all hotels

if one of the the 5 checkbuttons are enabled/clicked it should only show the hotel with that hotel star

if multiple checkbuttons are enabled/clicked it should only show those hotels with those stars;

I tried doing something like this

code:

                if (dto.Star1)  
                    rooms = rooms.Where(x => x.Stars == 1);  
  
                if (dto.Star2)  
                    rooms = rooms.Where(x => x.Stars == 2);  
  
                if (dto.Star3)  
                    rooms = rooms.Where(x => x.Stars == 3);  
  
                if (dto.Star4)  
                    rooms = rooms.Where(x => x.Stars == 4);  
  
                if (dto.Star5)  
                    rooms = rooms.Where(x => x.Stars == 5);  
  

If one of the Checkbuttons is clicked/enabled it works perfect but if I click enable mutliple checkbottons it returns nothing

Help me out with this please.

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
697 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,187 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,270 questions
0 comments No comments
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 56,686 Reputation points
    2022-07-25T20:49:42.27+00:00

    you want to generate an in clause:

    var starList = new List<int>();  
          
    if (dto.Star1) starList.Add(1);   
    if (dto.Star2) starList.Add(2);   
    if (dto.Star3) starList.Add(3);   
    if (dto.Star4) starList.Add(4);   
    if (dto.Star5) starList.Add(5);   
      
    var  query = rooms.Where(x => starList.Contains(x.Stars));  
      
      
      
    

2 additional answers

Sort by: Most helpful
  1. AgaveJoe 26,136 Reputation points
    2022-07-25T20:02:26.163+00:00

    I cannot see your code but something like the following pattern.

    var results = DbContext.Rooms.Where(x => (x.Stars == 1 & dto.Star1) |  
        (x.Stars == 2 & dto.Star2) |   
        (x.Stars == 3 & dto.Star3) |   
        (x.Stars == 4 & dto.Star4) |  
        (x.Stars == 5 & dto.Star5)).ToList();  
    
    0 comments No comments

  2. osyris 236 Reputation points
    2022-07-25T20:20:03.11+00:00

    Thank you very much Joe,

    I have tried to look up this problem for a couple of hours now,
    Could you explain how it works im curious.

    I know that "||" means OR, but what is "|"?
    and what is a single & sign?

    Is this a conditional operator inside a LINQ ?
    I have never seen that but that would be pretty genius