开发者

linq distinct not giving distinct results

开发者 https://www.devze.com 2022-12-16 19:42 出处:网络
I am pasting my code below; My base class is overriding Equals and getHashcode but the linq query is not returning distinct results. There are multiple cities in the results that have the same ID.

I am pasting my code below;

My base class is overriding Equals and getHashcode but the linq query is not returning distinct results. There are multiple cities in the results that have the same 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; }

 开发者_Go百科       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();


the query is executed at server side (in database). overriding equals or gethashcode doesn't make any difference.

Just select the id attribute and then call Distinct in the end. You'll have to iterate over the result to get more information though.

OR

You can use a join to get the details of the IDs returned from subquery.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消