How to join two arrays with linq

I am trying to combine two arrays with my relationships, but I can not do it strictly. I have a message table in my database, and there are questions and answers in the Records table. the answers are related to the question about the column "relatedPostId". eg:

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 looks 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 post messages to a ListBox (lstCurrentTopic.Items.AddRange (...)) I also want to display the answers at the end of each question, for example

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 this order to the list

+3
source share
2 answers

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;
              }

- LINQ to Entities, SQL, . LINQ , , :

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>()
              }
+5

, - :

var result =    from q in questions
                join a in answers on q.Id equals a.RelatedPostId
                group a by q;

, , :

var result =    from q in questions
                from a in answers.Where(x => x.RelatedPostId == q.Id).DefaultIfEmpty()
                group a by q;

IGrouping, , ( ).

var dict = result.ToDictionary(x => x.Key, x => x.Select(y => y));

, IEnumerable .

+2

Source: https://habr.com/ru/post/1780256/


All Articles