tags:

views:

47

answers:

2

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?

+1  A: 
var result = from question in questions where question.Id=3 
             select new 
             {
                 question = question, 
                 answers = from answer in answers where answer.questionId=3 
             }
Hasan Khan
hi thanks, but i know how to do this.. and as kirks answer below i have relationships and it works fine. i just want the entire result in 1 row.output must be as follows: questionid, question,answer1,answer2,answer3
Aneef
+1  A: 

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.

Kirk Woll
thanks kirk. oops i forgot linq can do this .. anyway thanks for the reminder :)
Aneef