我有 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);
关于c# - 与linq的连接查询不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33055023/