Interval data type for C# .NET?

前端 未结 8 1869
一个人的身影
一个人的身影 2021-01-30 23:07

I\'m looking an interval data type for .NET 4.0. For example the interval (a,b], all point x such that a

What i would like to be able to do are create interv

8条回答
  •  别那么骄傲
    2021-01-30 23:30

    I'd generally use the standard .NET Framework classes.

    int a = 2;
    int b = 10;
    
    // a < x <= b
    var interval1 = new HashSet(Enumerable.Range(a + 1, b - a));
    
    // Dump is a LINQPad extension method.
    interval1.Dump();
    // 3..10
    
    // Check if point in interval
    interval1.Contains(a).Dump();
    // False
    interval1.Contains(b).Dump();
    // True
    
    var overlappingInterval = new HashSet(Enumerable.Range(9, 3));
    overlappingInterval.Dump();
    // 9, 10, 11
    
    var nonOverlappingInterval = new HashSet(Enumerable.Range(11, 2));
    nonOverlappingInterval.Dump();
    // 11, 12
    
    interval1.Overlaps(overlappingInterval).Dump();
    // True
    
    interval1.Overlaps(nonOverlappingInterval).Dump();
    // False
    
    interval1.UnionWith(overlappingInterval);
    interval1.Dump();
    // 3..11
    // Alternately use LINQ's Union to avoid mutating.
    // Also IntersectWith, IsSubsetOf, etc. (plus all the LINQ extensions).
    

    EDIT: If you want to enforce that this is an interval instead of a set (and/or enforce immutability) you could wrap this in a custom class.

提交回复
热议问题