3

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.

Tarc
  • 3,214
  • 3
  • 29
  • 41
user629926
  • 1,910
  • 2
  • 18
  • 43
  • 1
    This is not a trivial question and does not deserve the down vote. In C++ there's a whole complex library only dealing with that https://www.boost.org/doc/libs/1_71_0/libs/icl/doc/html/index.html It's a shame there's no such a thing in C# only half baked forum posted implementations. – Tarc Oct 11 '19 at 20:39
  • Do you want a dynamic container, that allows adding/removing elements all the time, or a static one that is populated once and then only searched? – Theodor Zoulias Oct 11 '19 at 21:45
  • Related: [A dictionary object that uses ranges of values for keys](https://stackoverflow.com/questions/2147505/a-dictionary-object-that-uses-ranges-of-values-for-keys) – Theodor Zoulias Oct 11 '19 at 22:33

4 Answers4

1

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

Emmanuel
  • 3,475
  • 6
  • 29
  • 45
1

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.

Saeed Amiri
  • 22,252
  • 5
  • 45
  • 83
0

No. You should be able to use LINQ to perform such check on simple array of pairs.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • I think @Saeed Amiri's `Interval` example is going to make OP's code a lot clearer. – zmbq Mar 05 '12 at 22:39
-1

Use the TimeSpan struct.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
David Savage
  • 760
  • 5
  • 15