2011-09-08 110 views
3

我正在研究存储结构的最佳方法,并使其能够轻松搜索返回键的单个值。这里是pseduo数据结构:C#映射指南针点和搜索

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 

我希望能够将这些值存储在一个方式,我可以这样说:

给我一个给定值的键值。所以如果我需要193的密钥,我会退还SSW。我一直在玩弄不同的想法,但想看看你们的想法。

我以风向为例,但数据可能是任何东西。

数据结构将被编译并且永不改变。

谢谢。

回答

1

你可以创建一个类持有指南针值的“钥匙”(我认为“name”是一个比较合适的描述,但叫什么你想要什么)和范围,例如:

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

然后,创建类,它创建了一个静态List<CompassRange>并适当填充:

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

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

最后,您可以添加到这个类中的方法,将搜索的List为适当的范围,并返回名称:

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

你甚至可以使用内置的System.Tuple<string, int, int>型,而不是CompassRange尽管这牺牲了这些代码的一些清晰度。

+0

内置元组(在.NET 4.0的情况下) – sll

+0

甜甜甜圈!你的例子使我使用一个Tuple <>来避免不需要的类,这是一个非常干净的方法。我将用最终解决方案更新我的问题。 – slimflem

1

如果存储的最小,最大和方向的类,你可以很容易地只填充这些列表,并与一个单一的LINQ查询找到了方向:

// 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);