繁体   English   中英

与 linq 的连接查询不同

[英]Distinct in join query with linq

我有 3 行具有相同的 CommentingAuthor,我如何做不同的事情才能获得 1 个 CommentingAuthor ???

 IEnumerable<CommentingAuthor> CommentingAuthor =
                        from p in db.Posts
                        join c in db.Comments on p.WebSite equals c.CommentWebSite
                        select new CommentingAuthor
                        {
                            PostAuthorName = p.PostAuthor,
                            AuthorProfilePicture = c.CommentWebSite
                        };            

            return View(CommentingAuthor);

您可以使用Distinct 您可能必须实现自己的自定义比较器。

var uniqueCommentingAuthors = CommentingAuthor.Distinct();

使用客户比较器:

public class CommentingAuthorComparer : IEqualityComparer<CommentingAuthor>
{
    public bool Equals(CommentingAuthor author, CommentingAuthor author2)
    {
        return author.PostAuthorName.Equals(author2.PostAuthorName);
    }

    public int GetHashCode(CommentingAuthor author)
    {
        return author.PostAuthorName.GetHashCode();
    }
}

然后你可以像这样使用它:

   var comparer = new CommentingAuthorComparer();
   var uniqueAuthors = CommentingAuthor.Distinct(comparer);
   return View(uniqueAuthors);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM