Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interval container in C#

Is there any interval container in C#?

I'm interested in that it combines overlapping internals, and that I can find intervals that are not in the container but are in a specific interval.

like image 470
user629926 Avatar asked Dec 04 '25 16:12

user629926


2 Answers

Someone by the name of Jani Giannoudis has posted a .NET time period library on CodeProject that might fit your needs.

like image 156
Emmanuel Avatar answered Dec 06 '25 06:12

Emmanuel


You should implement a class like below:

public class Interval
{
   public long Start {get;set;}
   public long End{get;set;}

   public bool IsIn(Interval interval)
   {
      return Start >= interval.Start && End < interval.End;
   }

   public Interval Intersection(Interval interval)
   {
      if (interval == null)
        return false;

      if (IsIn(interval))
         return interval;
      if (interval.IsIn(this))
         return this;
      if ....
   }

   public Interval Union(Interval interval)
   {....}

   public bool IsIn(List<Interval> intervals)
   {
       return intrvals.Any(x=>IsIn(x));
   }

   public List<Interval> Intersect(List<Interval> intervals)
   {....}

   public List<Interval> Union(List<Interval> intervals)
   {....}
}

Edit: As @zmbq mentioned in comments, this can be done by struct, struct is more trivial way in this situations, I personally used class to simply deal with empty intervals (In fact if start - end >= 0, then interval is empty, instead of using predifined empty interval, I think we can set it to null. but I think this is syntax suger.

like image 35
Saeed Amiri Avatar answered Dec 06 '25 05:12

Saeed Amiri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!