2015-10-10 62 views
2

我得到3行相同的評論作者,我如何做不同得到1 CommentingAuthor?與linq加入查詢不同

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); 
+0

'CommentingAuthor.Distinct()'應該工作。 –

回答

1

您可以使用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); 
+0

我試了一下,但它顯示相同,我返回uniqueCommentingAuthors吧? – user3077648