Dolaps
Dolaps

Reputation: 279

List variable inside a query Linq

I have created a variable that returns a list ids of menus from the database. I have then put the variable in another query that returns meals in a list. My issue is that I keep on recieving the error Cannot implicitly convert type System.Collections.Generic.List<int?> to int?

var getmenuids = (from r in db.Menus
                  where (r.Restaurantid == currentrestaurant)
                  select r.Id).ToList();

var meals = db.Meals.Where(r => r.MenuID = getmenuids).ToList();

Upvotes: 1

Views: 2142

Answers (3)

JaredPar
JaredPar

Reputation: 754545

The problem here is that getmenuids is a collection of int? values but you compare it to r.MenuID which is typed to int?. To fix this you need to search getmenuids for r.MenuId

db.Meals.Where(r => getmenuids.Contains(r.MenuID)).ToList();

Upvotes: 3

voddy
voddy

Reputation: 1000

You are comparing the list with MenuID. getmenuids is a list.

r.MenuID = getmenuids

Upvotes: 0

Grant Winney
Grant Winney

Reputation: 66439

You're having an issue because you're using == (comparing a single element to a list) instead of Contains() (searching for the an element in the list).

var meals = db.Meals.Where(r => getmenuids.Contains(r.MenuID)).ToList();

You could combine these too.. something like this:

var meals = (from meal in db.Meals
             join menu in db.Menus on meal.MenuID equals menu.Id
             where menu.Restaurantid == currentrestaurant
             select meal).ToList();

Upvotes: 5

Related Questions