开发者

C# mapping compass points and searching

开发者 https://www.devze.com 2023-04-03 09:02 出处:网络
I am researching the best way to store a structure and have it easily searchable for a single value returning the key.Here is the pseduo data structure:

I am researching the best way to store a structure and have it easily searchable for a single value returning the key. Here is the pseduo data structure:

N = 0
NNE = 1 .. 44
NE = 45
ENE = 46 .. 89
E = 90
ESE = 91 .. 134
SE = 135
SSE = 136 .. 179
S = 180
SSW = 181 .. 224
SW = 225
WSW = 226 .. 269
W = 270
WNW = 271 .. 314
NW = 315
NNW = 316 .. 359

I would like to be able to store these values in a way that I can sa开发者_高级运维y something like:

Give me the key value for a given value. So if I need the key for 193, I would be returned SSW. I have been playing around with different ideas, but want to see what you guys think.

I am using wind direction as the example, but the data could be whatever.

The data structure will be compiled and never changes.

Thanks.


You could create a class to hold a "key" (I think "name" is a more appropriate descriptor, but call it what you wish) and range of values on the compass, e.g.:

public class CompassRange
{
   public string Name { get; set; }
   public int Min { get; set; }
   public int Max { get; set; }
}

Then, create class which creates a static List<CompassRange> and populate it appropriately:

public class Compass
{
    private static List<CompassRange> _ranges;

    static Compass()
    {
       _ranges = new List<CompassRange>()
       {
          // Add CompassRange objects here
       };
    }
}

Finally, you can add a method to this class that will search the List for the appropriate range and return the name:

public static string GetName(int direction)
{
    direction = direction % 360;
    return _ranges.First(x => x.Min <= direction && x.Max >= direction).Name;
}

You could even use the built-in System.Tuple<string, int, int> type instead of CompassRange, although this sacrifices some of the clarity of this code.


If you store the Min, Max, and Direction in a class, you could easily just populate a list of these, and find a direction with a single LINQ query:

// Given:
class Direction
{
     public Direction(string dir, int min, int max)
     {
         MinHeading = min;
         MaxHeading = max;
         Direction = dir;
     }
     public int MinHeading { get; private set; }
     public int MaxHeading { get; private set; }
     public string Direction { get; private set; }
}

// And a collection:
var directions = new List<Direction>
               {
                   new Direction("N",0,0),
                   new Direction("NNE",1,44),
                   ...
               }

// You can find a direction given
int compassHeading = 93;
string direction = directions
                   .First(d => compassHeading >= d.MinHeading && compassHeading <= d.MaxHeading)
                   .Select(d => d.Direction);
0

精彩评论

暂无评论...
验证码 换一张
取 消