C# 使用linq的连接查询中的Distinct
我有3行有相同的注释作者,我怎么做才能得到1个注释作者C# 使用linq的连接查询中的Distinct,c#,asp.net-mvc,linq,C#,Asp.net Mvc,Linq,我有3行有相同的注释作者,我怎么做才能得到1个注释作者 IEnumerable<CommentingAuthor> CommentingAuthor = from p in db.Posts join c in db.Comments on p.WebSite equals c.CommentWebSite select new Comme
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);
IEnumerable CommentingAuthor=
从数据库中的p.Posts
在db中加入c。在p.WebSite上的评论等于c.CommentWebSite
选择新注释作者
{
PostAuthorName=p.PostAuthor,
AuthorProfilePicture=c.CommentWebSite
};
返回视图(注释作者);
您可以使用。您可能必须实现自己的自定义比较器
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();
}
}
我尝试过,但它显示的是相同的,我返回uniqueCommentingAuthors,对吗?
CommentingAuthor.Distinct()
应该可以工作。
var comparer = new CommentingAuthorComparer();
var uniqueAuthors = CommentingAuthor.Distinct(comparer);
return View(uniqueAuthors);