0

I'm trying to write a semi convoluted query :-

The query should select a random selection of rows from a table which do not have a matching entry in a linking table. I.e

dishes
----
id
name


food
----
id
name

foodInDishes
----
food_id
dish_id

So what I am trying to accomplish is select the top most 10 rows where a user does not have a specific food. So

"Give me 10 dishes that I can make which do not contain carrots"

In C# I have a List<int> of foods to avoid. So far I have got too :-

List<int> oFoodsToAvoid = new List<int>();
var oDishes= db.dishes.OrderBy(r => Guid.NewGuid()).Take(10);

However I am struggling with the foods to avoid where clause. The problem I am facing is because it's a child table (i.e items.foods.id ). Any suggestions on what the where clause should contain?

1 Answer 1

1

You can use a simple nested lambda to achieve this. If oFoodsToAvoid is large, you could probably sort it before querying and then use Array.BinarySearch() in your nested lambda:

List<int> oFoodsToAvoid = new List<int>();
var oDishes= db.dishes.Where(d => !d.foods.Any(df => oFoodsToAvoid.Any(arr => arr == df.food_id)))
                       .OrderBy(r => Guid.NewGuid()).Take(10);
1
  • Unfortunately this only queries the dishes table, I'm needing to query the foods table attached to dishes (ie r.foods.id not r.id ) this is where I'm currently getting 'hung up'.
    – nyxthulhu
    May 8, 2014 at 3:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.