user3338918
user3338918

Reputation: 15

LINQ - joining two tables and geting the result in a viewmodel that has a different structure

Any help/hint on how to write LINQ to achieve the below will be much appreciated.

Data model:

public class Question
{
 public int ID { set; get; }
 public string QuestionText { set; get; }

}

public class Answer
{
 public int ID { set; get; }
 public int QuestionID { set; get; }
 public string AnswerText { set; get; }
}

View Model:

public class QuestionViewModel
{
 public int ID { set; get; }
 public string QuestionText { set; get; }
 public IEnumerable<AnswerViewModel> Answers { set; get; }

}

public class AnswerViewModel
{
 public int ID { set; get; }
 public string AnswerText { set; get; }
}

public class EvaluationViewModel
{
  public IEnumerable<QuestionViewModel> Questions { set; get; }
}

How can I write a LINQ query to join the models Question and Answer and write the rows into the EvaluationViewModel structure please?

Could it be done in one LINQ query? Or do we have to write a LINQ to join the models Question and Answer and then write something separate to get the data into EvaluationViewModel structure?

Thank you for any help on this.

Actually, I got this ViewModel structure from: http://www.techiesweb.net/radio-button-list-in-asp-net-mvc/

Upvotes: 1

Views: 2421

Answers (1)

thepirat000
thepirat000

Reputation: 13124

Assuming you have two collections: Questions and Answers:

IEnumerable<Question> Questions;
IEnumerable<Answer> Answers;

You can do it like this:

var vm = new EvaluationViewModel();
vm.Questions = 
    Questions.Select(q => new QuestionViewModel()
    {
        ID = q.ID,
        QuestionText = q.QuestionText,
        Answers = Answers.Where(a => a.QuestionID == q.ID).Select(a => new AnswerViewModel()
        {
            ID = a.ID,
            AnswerText = a.AnswerText
        })
    });

Upvotes: 2

Related Questions