Right way to implement GetHashCode for this struct

前端 未结 7 1897
庸人自扰
庸人自扰 2021-02-13 06:13

I want to use a date range (from one date to another date) as a key for a dictionary, so I wrote my own struct:

   struct DateRange
   {
      public DateTime St         


        
7条回答
  •  梦如初夏
    2021-02-13 06:58

    Since DateTime.GetHashCode is internally based on Ticks, what about this:

        public override int GetHashCode()
        {
            return unchecked((int)(Start.Ticks ^ End.Ticks));
        }
    

    Or, since you seem to be interested by the date parts (year, month, day), not the whole thing, this implementation uses the number of days between the two dates and should give almost no collision:

            public override int GetHashCode()
            {
                return unchecked((int)Start.Date.Year * 366 + Start.Date.DayOfYear + (End.Date - Start.Date).Days);
            }
    

提交回复
热议问题