Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to join two arrays with linq

Tags:

c#

linq

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

like image 493
Yucel Avatar asked Feb 25 '23 14:02

Yucel


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

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>()
              }
like image 69
StriplingWarrior Avatar answered Feb 28 '23 04:02

StriplingWarrior