In clause in linq expression

﹥>﹥吖頭↗ 提交于 2020-03-06 09:05:36

问题


i am developing a online test application where have two tables category and subCategory from which i want to select some questions with the help of category and subcategory. something like ( question where category ID in (1) and subcategoryID in (1,2,3,4)

I am getting list of subcategory that is going to pass in query

int[] subCategoryForQuestions=new int[]{1,2,3,4};

var TestDataList = coreDbContext.SolutionMasters
                       .Where(x => x.CategoryID == categoryID
                                   && x.DifficultyId == questionLevel
                                   && subCategoryForQuestions.Contains("here all value in Subcategory"))
                      .Take(NoOfQuestions);

or something like subcategoryID.contains("some value in array of integer")

can i get some help from anybody?


回答1:


You could use Contains as per https://blogs.msdn.microsoft.com/alexj/2009/03/25/tip-8-how-to-write-where-in-style-queries-using-linq-to-entities/ and Linq to Entities - SQL "IN" clause .

int[] subCategoryForQuestions=new int[]{1,2,3,4};

var TestDataList = coreDbContext.SolutionMasters
                       .Where(x => x.CategoryID == categoryID
                                   && x.DifficultyId == questionLevel
                                   && subCategoryForQuestions.Contains(x.subcategoryID))
                      .Take(NoOfQuestions);

This will generate an IN statement behind the scenes. You will want to ensure that the array is relatively small so you don't exhaust the SQL Server parameter limit.



来源:https://stackoverflow.com/questions/44991481/in-clause-in-linq-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!