Use a SortedList<int, int> and SortedList<int, int> over it until you find a value that is greater than the value you are looking for. You can do this using a simple iteration, as in the answer you already accepted. Or it can be done elegantly using LINQ (at a low execution cost):
SortedList<int, int> levels = new SortedList<int, int> { {0, 1}, {100, 2}, {200, 3}, {400, 4}, {600, 5}, }; public int Experience; public int Level { get { return levels.Last(kvp => Experience >= kvp.Key).Value; } }
Note that maintaining the βlevelβ is not really strictly necessary, since you can get it from the index of an item in a list. It may be beneficial to use a simple List<int> , which is sorted instead, to prevent errors when you accidentally miss a level, as in a decision you have already made.
If you need better performance, you can use List.BinarySearch , but I think that the additional complexity is not worth it if you do not have a profile profile and that this is a bottleneck.
List<int> levels = new List<int> { 0, 100, 200, 400, 600 }; int index = levels.BinarySearch(Experience); int level; if (index < 0) { level = ~index; } else { level = index + 1; } return level;
Mark byers
source share