i am trying to combine two arrays with their relations but cant do exatly. I have a Posts Table on my database and in Posts table there are questions and answers records. answers are related with question on "relatedPostId" column. ex:
Posts (Table)
-------------
int Id (Field)
string Text (Field)
int RelatedPostId (Field)
question(record) : relatedPostId column is null
answer(record) : relatedPostId column is the value of question id
My code is like below
var posts = DBConnection.GetComments(_post.TopicId).ToArray().OrderByDescending(p => p.CreateDate);
var questions = posts.Where(p => p.RelatedPostId == null);
var answers = posts.Where(p => p.RelatedPostId != null);
var result = from q in questions
join a in answers
on q.Id equals a.RelatedPostId
select new { q = q, a = a };
I want to list posts on a ListBox (lstCurrentTopic.Items.AddRange(...)) Also i want to display answers at the end of each question like
Question1
-> Answer1 (relatedPostId is Qustion1.Id)
-> Answer2 (relatedPostId is Qustion1.Id)
Qestion2
->Answer3 (relatedPostId is Qustion2.Id)
->Anser4 (relatedPostId is Qustion2.Id)
how can i add with this order to listbox
Something like this should work:
var result = from q in questions
select new {
q,
answers =
from a in answers
where q.Id == a.RelatedPostId
select a;
}
The above approach would work great for something like LINQ to Entities, where it gets translated to a SQL statement that the database can optimize. Since you're using LINQ to objects, you'll get better performance if you take advantage of data structures:
var answersByQuestionId = answers.ToLookup(a => a.RelatedPostId);
var result = from q in questions
select new {
q,
answers = answersByQuestionId.Contains(q.Id)
? answersByQuestionId[q.Id].AsEnumerable()
: Enumerable.Empty<Answer>()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With