Another alternative:
public enum Direction
{
North = 0,
NorthEast = 1,
East = 2,
SouthEast = 3,
South = 4,
SouthWest = 5,
West = 6,
NorthWest = 7
}
public static class DirectionExtensions
{
private static readonly Dictionary<Direction, string>
mapping = new Dictionary<Direction, string>
{
{ Direction.North, "n" },
{ Direction.NorthEast, "ne" },
{ Direction.East, "e" },
{ Direction.SouthEast, "se" },
{ Direction.South, "s" },
{ Direction.SouthWest, "sw" },
{ Direction.West, "w" },
{ Direction.NorthWest, "nw" }
};
public static bool IncludesHeading(this Direction direction, int heading)
{
var adjusted = (heading + 22) % 360;
var adjMin = (int) direction * 45;
var adjMax = adjMin + 44;
return (adjusted >= adjMin && adjusted <= adjMax);
}
public static string GetSuffix(this Direction direction)
{
return mapping[direction];
}
}
Leaves your method reading like this:
public string GetHeadingImage(string imageName, int heading)
{
Direction[] directions = ((Direction[]) Enum.GetValues(typeof(Direction)));
var match = directions.First(d => d.IncludesHeading(heading));
return imageName + match.GetSuffix() + ICON_FILE_EXTENTION;
}
[Edit: Taking that one step further]
Replace the IncludesHeading extension with
public static IntDirectionExtensions
{
public static Direction GetDirection(this int heading)
{
var adjusted = (heading + 22) % 360;
var sector = adjusted / 45;
return (Direction)sector;
}
}
And now you can simplify your method to
public string GetHeadingImage(string imageName, int heading)
{
return imageName + heading.GetDirection().GetSuffix() + ICON_FILE_EXTENTION;
}
[Edit 2: Another idea]
Another thing you could do is map to the suffix via reflection, which I think looks nicer but is probably less efficient
public enum Direction
{
[IconSuffix("n")] North = 0,
[IconSuffix("ne")] NorthEast = 1,
[IconSuffix("e")] East = 2,
[IconSuffix("se")] SouthEast = 3,
[IconSuffix("s")] South = 4,
[IconSuffix("sw")] SouthWest = 5,
[IconSuffix("w")] West = 6,
[IconSuffix("nw")] NorthWest = 7
}
public class IconSuffixAttribute : Attribute
{
public string Suffix { get; private set; }
public IconSuffixAttribute(string suffix)
{
Suffix = suffix;
}
}
Replacing your GetSuffix extension (and now-defunct Dictionary mapping) with
public static string GetSuffix(this Direction direction)
{
var suffix = from m in typeof(Direction).GetMember(direction.ToString())
from a in m.GetCustomAttributes(typeof(IconSuffixAttribute), false)
select ((IconSuffixAttribute) a).Suffix;
return suffix.First();
}
Everything else remains the same.