Check if a date range is within a date range

前端 未结 8 2120
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-09 06:01

I have the following class:

public class Membership
{
    public DateTime StartDate { get; set; }
    public DateTime? EndDate { get; set; } // If null then          


        
8条回答
  •  臣服心动
    2020-12-09 06:35

    Here's a solution (missing null argument-validation, and validation within Membership that EndDate > StartDate) using Collection:

    public class Membership
    {
        public DateTime StartDate { get; set; }
        public DateTime? EndDate { get; set; } // If null then it lasts forever
    
        private DateTime NullSafeEndDate { get { return EndDate ?? DateTime.MaxValue; } }  
    
        private bool IsFullyAfter(Membership other)
        {
           return StartDate > other.NullSafeEndDate;
        }
    
        public bool Overlaps(Membership other)
        {
          return !IsFullyAfter(other) && !other.IsFullyAfter(this);
        }
    }
    
    
    public class MembershipCollection : Collection
    {
       protected override void InsertItem(int index, Membership member)
       {
           if(CanAdd(member))
              base.InsertItem(index, member);
           else throw new ArgumentException("Ranges cannot overlap.");
       }
    
       public bool CanAdd(Membership member) 
       {
           return !this.Any(member.Overlaps);
       }
    }
    

提交回复
热议问题