2011-09-08 56 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);