Home > OS >  why can't I write two conditions ? how can I fix this problem?
why can't I write two conditions ? how can I fix this problem?

Time:03-31

List<MasterQuestion> questions = _sql.MasterQuestions
    .Include(x => x.MasterQuestionVariants)
    .Where(x => x.MasterQuestionExamId == ed.ExamMasterDetailExamId 
             && x.MasterQuestionSectorId == ed.ExamMasterDetailSectorId 
             && x.MasterQuestionSubjectId == 6 
             && x.MasterQuestionSubjectId == 7)
    .ToList();

can I get two or more equality from same column

CodePudding user response:

There's a couple of ways to do this. Either use an || operator (i.e. OR instead of AND) for the MasterQuestionSubjectId or Contains. For example (note the extra brackets):

List<MasterQuestion> questions = _sql.MasterQuestions
    .Include(x => x.MasterQuestionVariants)
    .Where(x => x.MasterQuestionExamId == ed.ExamMasterDetailExamId 
             && x.MasterQuestionSectorId == ed.ExamMasterDetailSectorId 
             && (x.MasterQuestionSubjectId == 6 || x.MasterQuestionSubjectId == 7))
    .ToList();

Or this which is more readable and extensible since you can add more than one ID to the array and the query doesn't get even worse to read:

var ids = new [] { 6, 7 };

List<MasterQuestion> questions = _sql.MasterQuestions
    .Include(x => x.MasterQuestionVariants)
    .Where(x => x.MasterQuestionExamId == ed.ExamMasterDetailExamId 
             && x.MasterQuestionSectorId == ed.ExamMasterDetailSectorId 
             && ids.Contains(x.MasterQuestionSubjectId))
    .ToList();
  • Related