I have following list:
100 -> 1.0
99 -> 1.1
98 -> 1.1
97 -> 1.2
...
23-28 -> 5.6
...
0-5 -> 6.0
On the left side are the maximal reached points, on the right side the grade.
This list contains around 40 different Points -> Grade. So my program is calculating the points of the exam, and in the end it should say 100 Points reached, u got the grade 1.0 ... 3 Points reached -> 6.0 ...
On my current knowledge, I know only switch case, but I think it's not the best way to realize it.
I'd start off with a data structure for the list you have. (This is assuming C# 6, by the way - for earlier versions of C# you wouldn't be able to use an auto-implemented readonly property, but that's about the only difference.)
public sealed class GradeBand
{
public int MinScore { get; }
public int MaxScore { get; } // Note: inclusive!
public decimal Grade { get; }
public GradeBand(int minScore, int maxScore, decimal grade)
{
// TODO: Validation
MinScore = minScore;
MaxScore = maxScore;
Grade = grade;
}
}
You can construct your list with:
var gradeBands = new List<GradeBand>
{
new GradeBand(0, 5, 6.0m),
...
new GradeBand(23, 28, 5.6m),
...
new GradeBand(100, 100, 1.0m),
};
You'd probably want some sort of validation that the bands covered the whole range of grades.
Then there are two fairly obvious options for finding the grade. Firstly, a linear scan with no preprocessing:
public decimal FindGrade(IEnumerable<GradeBand> bands, int score)
{
foreach (var band in bands)
{
if (band.MinScore <= score && score <= band.MaxScore)
{
return band.Grade;
}
}
throw new ArgumentException("Score wasn't in any band");
}
Or you could preprocess the bands once:
var scoreToGrade = new decimal[101]; // Or whatever the max score is
foreach (var band in bands)
{
for (int i = band.MinScore; i <= band.MaxScore; i++)
{
scoreToGrade[i] = band.Grade;
}
}
Then for each score you can just use:
decimal grade = scoreToGrade[score];
See more on this question at Stackoverflow