Barry Franklin
Barry Franklin

Reputation: 1820

Linq way to check a property of one set against a property of another set

So I have this need to check the answer of a question against the correct answer from the database.

Obj1.Answer == Obj2.CorrectAnswer

And I know I can do something like this:

List<SimpleQuestion> listOfQ = {from user}
List<Question> testQuestions = {from db}
List<Question> correctAnswers = new List<Question>();
for (int i = 0; i < listOfQ.Count(); i++)
{
   var item = testQuestions.Where(t => t.QuestionId.ToString() == listOfQ[i].QuestionId).FirstOrDefault();
   if (item != null)
   {
     if (listOfQ[i].Answer == item.CorrectAnswer.ToString())
     {
        correctAnswers.Add(item);
     }
   }               
}

But is there a way to do this in one linq statement where Obj1.Answer == Obj2.CorrectAnswer returns a list of objects that match? This code works fine for me, I'm just curious if there was a linq way to do it - if there is I can't seem to figure it out.

Upvotes: 0

Views: 90

Answers (3)

Ghassen
Ghassen

Reputation: 1206

Our Model Classes:

public class Question
    {
        public int Iduser;
        public int IdQuestion;
        public string Answer;
        public Question(int iduser,int idquestion,string answer)
        {
            this.Iduser = iduser;
            this.IdQuestion = idquestion;
            this.Answer = answer;
        }
    }

public class SimpleQuestion
{
    public int IdQuestion;
    public string Answer;
    public SimpleQuestion(int idquestion, string answer)
    {
        this.IdQuestion = idquestion;
        this.Answer = answer;
    }
}

Main:

List<SimpleQuestion> listOfQ = new List<SimpleQuestion>();
            listOfQ.Add(new SimpleQuestion(1, "1"));
            listOfQ.Add(new SimpleQuestion(2, "2"));
            listOfQ.Add(new SimpleQuestion(3, "3"));

            List<Question> testQuestions = new List<Question>();
            testQuestions.Add( new Question(1,1,"1"));
            testQuestions.Add( new Question(2,2,"2"));
            testQuestions.Add( new Question(3,3,"1"));


            List<Question> list = (from q in listOfQ
                                   join a in testQuestions on q.IdQuestion equals a.IdQuestion
                                   where a.Answer == q.Answer
                                   select a
                                      ).ToList();

Upvotes: 1

Robert McKee
Robert McKee

Reputation: 21477

correctAnswers=listOfQ.Join(testQuestions,
  a=>new {a.QuestionId,a.Answer},
  b=>new {b.QuestionId.ToString(),b.CorrectAnswer.ToString()},
  (a,b)=>b);

Upvotes: 2

Meysam Khoshbakht
Meysam Khoshbakht

Reputation: 310

I think your answer is here:

currectAnswers.AddRange(testQuestions.Where(
t=>listOfQ.Any(l=>l.QuestionId==t.QuestionId && 
l.Answer==t.CorrectAnswer))

Upvotes: 4

Related Questions