c# - LINQ 联合和不同

标签 c# linq union distinct

我有一个 C# .Net Web 应用程序,我正在使用以下 LINQ 查询来获取用户创建的或具有各种用户角色的不同提案列表。即使在 Union 和 Distinct 之后,要返回的列表也包含相同提案的重复内容。我做错了什么?

      var thereturn = FindAll(DetachedCriteria.For<Proposal>(),
                             new Order("CreateDate", false));

     //get the proposals that aUser created
     IList<Proposal> it = 
                thereturn.Where(proposal => proposal.CreatedBy.Equals(aUser)).ToList();

     //get the proposals that aUser is a BOE Author
     IList<Proposal> it2 =
          thereturn.Where(proposal =>
              proposal.BOEs.Any(boe =>
                  boe.Users.Where(a => a.Name == aUser).Any())).ToList();
     //get all other proposals that aUser is on
     IList<Proposal> it3 = 
          thereturn.Where(proposal =>
              proposal.Users.Where(o => o.Name == aUser).Any()).ToList();
     //now union with all other proposals that aUser is on
     return it3.Union(it).Union(it2).
               OrderByDescending(o=>o.CreateDate).Distinct().ToList();

最佳答案

Proposal 类的定义是什么?您可能对 Proposal 类的默认相等运算符有疑问。 As msdn says about Distinct :

Returns distinct elements from a sequence by using the default equality comparer to compare values.

编辑:换句话说,您是否有 Equals 和/或 GetHashCode 的自定义实现?

关于c# - LINQ 联合和不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10180386/

相关文章:

SQL - 如何通过连接将不同表中的 2 个日期合并在一起而不会出现错误

sql - 别名联合的结果

linq - 值或构造函数查询未定义

c# - 如何使用 linq dynamic 过滤子集合

c# - 热拖如何在 Visual Studio 2012 (C Sharp) 中使用变量或方法?

c# - 使用 Nhibernate 删除父项后删除多对多表中的所有记录

c# - 使用传入两个参数的linq查询实体

sql-server - 在SQL中获取最近的较高和较低的行

c# - Json.NET 中的 JConstructor 和 JRaw

c# - 使用多个查询字符串在 asp.net 3.5 中重写 URL