My tables are structured as below:
Questions
id title
1 what is this?
Answers
id answer qid
1 an 1
I want to select the question and all the answers in one single row through LINQ?
How can i do this?
My tables are structured as below:
Questions
id title
1 what is this?
Answers
id answer qid
1 an 1
I want to select the question and all the answers in one single row through LINQ?
How can i do this?
var result = from question in questions where question.Id=3
select new
{
question = question,
answers = from answer in answers where answer.questionId=3
}
In addition to Hasan's answer, if you are using LinqToSql and your relationships are properly established, then the code should simply be:
var question = questions.Single(x => x.Id == 3);
Answers should then already be available to you through the property:
var answers = question.Answers;
Since presumably you have an actual relationship defined between question.Id
and answer.Qid
.
Update:
In response to OP's comments, here is how you can get all the data back as one row:
var questionAndAnswers = questions
.Where(x => x.Id == 3)
.Select(x => new
{
QuestionId = x.Id,
Question = x.Title,
Answer1 = x.Answers[0].Answer,
Answer2 = x.Answers[1].Answer,
Answer3 = x.Answers[2].Answer
}).Single();
Will return an object with the question and 3 answers. Obviously adding more answers requires tweaking this statement, since it's flattened.