If you have a static list (changes are so infrequent that they're negligible), and you need immediate, ultra-high-speed access either way, you can use one of many simple C# features, I'm going to outline 2 major options: switch
or Dictionary
, however you need two of each for the fastest method.
You can use a programme to generate the code for you, but the examples are as follows:
Switch / Case
The first example is easy, build two methods, GetHexFromName
and GetNameFromHex
, and a switch
statement in them.
public static int GetHexFromName(string name)
{
switch (name)
{
case "Amaranth":
return 0xE52B50;
case "Amber":
return 0xFFBF00;
// Remaining 863 colors
default:
throw new ArgumentException();
}
}
public static string GetNameFromHex(int hex)
{
switch (hex)
{
case 0xE52B50:
return "Amaranth";
case 0xFFBF00:
return "Amber";
// Remaining 863 colors
default:
throw new ArgumentException();
}
}
Easy enough. You can build a quick tool that could generate the code for you, Roslyn would probably make it even easier.
You would call this as GetHexFromName(colorName)
.
Dictionaries
This is probably the method I would go along with, as access reads a bit better.
public static readonly ReadOnlyDictionary<string, int> Hex = new ReadOnlyDictionary<string, int>(new Dictionary<string, int> {
["Amber"] = 0xE52B00,
["Amaranth"] = 0xFFBF00,
// Remaining 863
});
public static readonly ReadOnlyDictionary<int, string> Name = new ReadOnlyDictionary<int, string>(new Dictionary<int, string> {
[0xE52B00] = "Amber",
[0xFFBF00] = "Amaranth",
// Remaining 863
});
This reads as Hex[colorName]
.
It's easy to adjust either of these to put the hex in string format. The ReadOnlyDictionary
is in the System.Collections.ObjectModel
namespace in the System.Collections.dll
library. The .NET Core version might not have that, so you may need to omit that from your code. Just trust that no one will call any methods on the Dictionary
types. I've also written this for C#6.0 syntax - you may need to alter that for your environment.
These are going to be your fastest options, especially if the list doesn't change frequently (or at all). The only problem is maintainability, but usually you sacrifice one of: maintainability, performance, simplicity. Here we sacrifice maintainability a bit, but we get a lot of performance.
Also, order shouldn't matter much in either of these cases: in the switch
option the compiler will generate the optimal code (we hope), in the Dictionary
option the JITter and Dictionary
implementation will optimize the structure. Reading from either of these should be fast.