c# - linq distinct 没有给出不同的结果

标签 c# .net

我在下面粘贴我的代码;

我的基类重写了 Equals 和 getHashcode,但 linq 查询没有返回不同的结果。结果中有多个具有相同 ID 的城市。

public class Product : EntityBase
   {
        public virtual string Name { get; set; }

        public virtual IList<ProductDayDefinition> Days { get; set; }
   }

   public class ProductDayDefinition : EntityBase
   {
        public virtual Product Product { get; set; }

        public virtual City City { get; set; }

    }


public abstract class EntityBase
    {
        public virtual int ID { get; protected internal set; }

        protected EntityBase() : this(0) 
        { 

        }

        protected EntityBase(int ID)
        {
            this.ID = ID;

            if (this.ID == null)
                this.ID = 0;
        }           

        #region Equals definitions
        public override bool Equals(object entity)
        {
            return entity != null
                && entity is EntityBase
                && this == (EntityBase)entity;
        }

        public static bool operator ==(EntityBase base1, EntityBase base2)
        {
            if ((object)base1 == null && (object)base2 == null)
                return true;

            if ((object)base1 == null || (object)base2 == null)
                return false;

            if (base1.ID != base2.ID)
                return false;

            return true;
        }

        public static bool operator !=(EntityBase base1, EntityBase base2)
        {
            return (!(base1 == base2));
        }

        public override int GetHashCode()
        {
            return this.ID.GetHashCode();
        }
        #endregion
    }

var cities = (from product in NHibernateSession.Linq<Product>() 
              from day in product.Days
              where day.City != null
              select day).Distinct();

最佳答案

查询在服务器端(在数据库中)执行。 覆盖 equals 或 gethashcode 没有任何区别。

只要选择id属性,最后调用Distinct即可。 不过,您必须遍历结果才能获得更多信息。

您可以使用联接来获取从子查询返回的 ID 的详细信息。

http://msdn.microsoft.com/en-us/library/cc716801.aspx

关于c# - linq distinct 没有给出不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2100482/

相关文章:

c# - 为什么 Interlocked.Exchange 不支持 Boolean 类型?

c# - 确保 HttpConfiguration.EnsureInitialized()

添加重复项时引发异常的 .NET 集合

.net - 如何使 System.Drawing.Image 半透明?

c# - 如何使用 .NET 框架设置作业调度?

c# - 如何使用 mstest 将输出文件添加到结果窗口?

与托管 API 通信的 Javascript?

c# - 如何在 linq to entity 中使用标量值函数?

c# - 怎么理解这个Unity Coroutine呢?

c# - 在移动设备中实现 Google map