【问题标题】:how to join two arrays with linq如何使用 linq 连接两个数组
【发布时间】:2010-12-15 02:41:38
【问题描述】:

我正在尝试将两个数组与其关系相结合,但无法做到。 我的数据库上有一个 Posts 表,在 Posts 表中有问题和答案记录。答案与“relatedPostId”列上的问题有关。 例如:

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

我的代码如下所示

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

我想在 ListBox 上列出帖子 (lstCurrentTopic.Items.AddRange(...)) 我还想在每个问题的末尾显示答案,例如

Question1
 -> Answer1 (relatedPostId is Qustion1.Id)
 -> Answer2 (relatedPostId is Qustion1.Id)
Qestion2
 ->Answer3 (relatedPostId is Qustion2.Id)
 ->Anser4 (relatedPostId is Qustion2.Id)

如何将此订单添加到列表框

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    这样的事情应该可以工作:

    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 to 对象,因此如果您利用数据结构,您将获得更好的性能:

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

    【讨论】:

      【解决方案2】:

      如果您只想要有答案的问题,那么您可以使用以下内容:

      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 作为值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-12
        • 2012-12-30
        • 1970-01-01
        相关资源
        最近更新 更多