c# - 与linq的连接查询不同

标签 c# asp.net-mvc 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);

关于c# - 与linq的连接查询不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33055023/

相关文章:

c# - 在数据透视表无法削减并且数据来自许多地方的情况下,如何自动化地按计划进行报告?

c# - 使用 C#.NET 1.1 的程序化 HTML POST

C# - 读取 XML 文件

c# - 不支持每种类型的多个对象集。对象集 IdentityUsers' 和 Users 都可以包含类型的实例

c# - Linq 返回 1 条记录

c# - 使用 ref 参数委托(delegate)

javascript - 使用 AJAX 将基于 JSON 的远程数据导入 Select2

c# - 来自默认 ASP.NET MVC 新项目的异步操作的解释?

c# - 无限期地重复可枚举

c# - 如何使用 C# 和 LINQ 深入提取 XML 中的信息?