简体   繁体   English

与 linq 的连接查询不同

[英]Distinct in join query with linq

I got 3 rows with same CommentingAuthor, how i do distinct to get 1 CommentingAuthor???我有 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);

You can use Distinct .您可以使用Distinct You may have to implement your own custom comparer.您可能必须实现自己的自定义比较器。

var uniqueCommentingAuthors = CommentingAuthor.Distinct();

Using a customer comparer:使用客户比较器:

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

Then you can use it like:然后你可以像这样使用它:

   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