Problem overview
In this version the data is no longer two parallel arrays. A SortedDictionary<string, int> named grades maps each subject to the student's score in it: Math 92, English 78, Science 85 and History 67. The program must print each subject with its letter grade, in alphabetical order of subject, using the usual scale: 90 and above is A, 80 to 89 is B, 70 to 79 is C, 60 to 69 is D, and below 60 is F.
The subjects were added in the order Math, English, Science, History, but the output is sorted:
English: C
History: D
Math: A
Science: B
Approach: loop over the keys, look up each score
A dictionary stores key and value pairs. To visit every subject, loop over grades.Keys, the collection of keys. For each key you read the value with grades[subject], which gives the score stored under that subject name.
The order of the output comes from the type of the dictionary. A SortedDictionary keeps its keys sorted at all times, so grades.Keys comes out from A to Z whatever the order of insertion. The loop therefore needs no sorting code. A plain Dictionary makes no promise about enumeration order, so it would not be a safe choice when the order of the output matters.
Inside the loop the work is the same as in the previous version: read the score, run the grade ladder, print one line. The only change is where the score comes from, the dictionary lookup in place of an array position.
Step by step
- Loop over the keys.
foreach (string subject in grades.Keys)givessubjecta new key on each pass, from English to Science. - Look up the score.
int score = grades[subject];reads the value stored under the current key. - Declare
gradeas astringwith no value yet. - Start the ladder with
if (score >= 90)and assign"A". The tests run from the top grade down, so later tests only need a lower bound. - Add the
else ifbranches for 80 (B), 70 (C) and 60 (D). Each is reached only when the earlier ones failed. - End with
elsefor the F, so that every score assigns a grade. - Print inside the loop, after the ladder:
subject + ": " + grade. One line per subject gives the four lines of output.
Tracing the sorted order: the first key is English, whose score is 78. The ladder fails the 90 and 80 tests, passes the 70 test, and the program prints English: C. History follows with 67 and gets a D, then Math with 92 gets an A, and Science with 85 gets a B.
The solution in C#
SortedDictionary<string, int> grades = new SortedDictionary<string, int>();
grades["Math"] = 92;
grades["English"] = 78;
grades["Science"] = 85;
grades["History"] = 67;
foreach (string subject in grades.Keys) {
int score = grades[subject];
string grade;
if (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else if (score >= 70) {
grade = "C";
} else if (score >= 60) {
grade = "D";
} else {
grade = "F";
}
Console.WriteLine(subject + ": " + grade);
}
Details worth knowing:
- The indexer both adds and replaces.
grades["Math"] = 92;adds the key when it is new and overwrites the value when it exists.grades.Add("Math", 1)on an existing key throws anArgumentExceptioninstead. - Reading a missing key throws.
grades["Music"]throws aKeyNotFoundExceptionwhen there is no such key. UseContainsKeyorTryGetValuewhen a key may be absent:TryGetValuereturnsfalseand gives0in itsoutvariable for a missing key. Inside this lesson's loop the key always exists, because it comes from the dictionary itself. - Keys are unique. Assigning to the same subject twice leaves one entry, holding the last value.
- Do not change the dictionary during the loop. Adding or removing entries inside a
foreachover its keys makes the next step of the loop throw anInvalidOperationException. The lesson only reads, so it is safe. - The type has two type arguments.
SortedDictionary<string, int>says keys are strings and values areint, which is whygrades[subject]can be stored directly in anint.
Edge cases and common mistakes
- Expecting insertion order. The subjects were inserted in a different order from the output. The sorted order is a property of
SortedDictionary. - Looping over
gradesdirectly. Looping over the dictionary itself givesKeyValuePairitems, not strings. That also works, withpair.Keyandpair.Value, but the lesson loops overgrades.Keysand looks up each value. - Adding a subject. If you add
grades["Art"] = 59;before the loop, the program printsArt: Fas the first line, because Art sorts before English. Withgrades["Math"] = 100;added, Math still gets an A and still stays between History and Science. - Boundary scores. A score of exactly 90 is an A and 59 is an F, so the tests use
>=. - Empty dictionary. With no subjects the loop never runs and nothing is printed.
Testing
- The starting data prints
English: C,History: D,Math: AandScience: B. - Adding
grades["Art"] = 59;and setting Math to 100 prints five lines, starting withArt: F, then English, History, Math and Science, with Math still an A.
The next version builds on this one.
