c# – 如何使用linq连接两个数组
发布时间:2020-12-16 01:39:47 所属栏目:百科 来源:网络整理
导读:我试图将两个阵列与他们的关系结合起来,但不能做得很好. 我的数据库和帖子表中有一个帖子表,有问题和答案记录.答案与“relatedPostId”栏中的问题有关. 例如: Posts (Table)-------------int Id (Field)string Text (Field)int RelatedPostId (Field)questi
我试图将两个阵列与他们的关系结合起来,但不能做得很好.
我的数据库和帖子表中有一个帖子表,有问题和答案记录.答案与“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) 如何将此订单添加到列表框中 解决方法
这样的事情应该有效:
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>() } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |