Aneef
Aneef

Reputation: 3729

LINQ multiple childs in 1 row

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?

Upvotes: 0

Views: 85

Answers (1)

Kirk Woll
Kirk Woll

Reputation: 77546

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.

Upvotes: 1

Related Questions