Search code examples
c#dictionarystructvariable-types

Using structs for Range variable type


I am trying to make a struct for a range variable (minimum, maximum) with a few members and a method to know if between values.

Right now my struct looks like this:

public struct NumRange
{
    float maximum;
    float minimum;

    public NumRange(float min, float max) 
    {
        this.maximum = max;
        this.minimum = min;
    }

    public bool IsBetween(float value)
    {
        if (value < maximum && value > minimum)
            return true;

        return false;
    }
}

I want to be able to make number ranges by

NumRange test = new NumRange(15, 20);

The whole point of making this range variable type is to make a map key dictionary like:

public Dictionary<NumRange, Color> mapKey = new Dictionary<NumRange, Color>();
NumRange test = new NumRange(15, 20);
mapKey.Add(test, Color.Orange);

Is this the best way to go about it? Also it doesn't like when I try to add something to mapKey. Says there is invalid tokens such as ',' ')' '('


Solution

  • Unless you have a finite number of values to look up, a dictionary may not be the best choice. It looks like you're mapping ranges of values to colors to apply to a height map. This stub of a class will let you do so, but note that it does not accommodate blending from color A to color B.

    class RangeMap<T>
    {
        private SortedList<float, T>  _values;
    
        public RangeMap()
        {
            _values = new SortedList<float, T>();
        }
    
        public void AddPoint(float max, T value)
        {
            _values[max] = value;
        }
    
        public T GetValue(float point)
        {
            if (_values.ContainsKey(point)) return _values[point];
    
            return (from kvp in _values where kvp.Key > point select kvp.Value)
                   .FirstOrDefault();
        }
    }   
    
    var  map = new RangeMap<Color>();
    map.AddPoint(0.0F, Color.Red);
    map.AddPoint(0.5F, Color.Green);
    map.AddPoint(1.0F, Color.Blue);
    
    Console.WriteLine(map.GetValue(-0.25F).Name);
    Console.WriteLine(map.GetValue( 0.25F).Name);
    Console.WriteLine(map.GetValue( 0.75F).Name);
    Console.WriteLine(map.GetValue( 1.25F).Name);
    

    Output: Red, Green, Blue, empty struct.