Pergunta

I've been having a problem involving filtering down a list based on 3 different types of list sources.

Suppose I have a very large list encompassing every hospital in the US. So I have 3 tables, a State table showing all hospitals for each state, a Cities table where I show all hosptials in Cities of each state, and a ZipCode table where I show all hospitals within a zipcode.

Here are a few scenarios of my search:

  • If I search on 2 states, NY and CA, I get a list of all the hospitals in those states.
  • If I add a a few cities, New York and Las Angeles, then the filter is zoomed down to those hospitals.
  • If I include a zipcode regardless of states or cities, like a zipcode in Alaska, then I show those (it still shows the hospitals selected for NYC, NY and Las Angeles, CA).

here's what I have so far:

(from hospitals in context.Hospitals)
 where HospitalIDsByState.Contains(hospitals.state) &&
       HospitalIDsByCity.Contains(hosptials.city) ||
       HospitalIDsByZipcodes(hospitals.zipcode)
 select hospitals)
  • HospitalIDsByState a list of IDs from a previous query filtered on selected states
  • HospitalIDsByCity is a list of IDs from a query filtered on selected cities
  • HospitalIDsByZipcodes is a list of IDs from a query filtered on selected zipcodes

the problem I have here is that if I selected States but my Cities is empty, I don't get any results, I need it to be filtered where if only States are selected, I can get a list, if Cities are selected, the list for that state is filtered, if zipcodes are selected, it includes that list of hospitals in the search results.

Foi útil?

Solução

Due to deferred execution, you can piece your query together more dynamically:

var query = context.Hospitals;
if (HospitalIDsByState.Any())
  query = query.Where(h => HospitalIDsByState.Contains(h.state));
if (HospitalIDsByCity.Any())
  query = query.Where(h => HospitalIDsByCity.Contains(h.city));
if (HospitalIDsByZipcodes.Any())
  query = query.Where(h => HospitalIDsByZipcodes(h.zipcode));

return query;

The advantage here is that only the relevant query parts are pushed to your database and you don't end up checking things that you don't need to.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top