Hi,
I would suggest that you take a look into the Filter entity from the Foundation Lib.
It does what you want as it composes a dynamic where statement from the given conditions (filters in select criteria).
After understanding how it works there, you should be able to build your own dynamic query generator adapting the metacode without too much effort.
I don't know if anyone has any better suggestion?