You could use Dictionary.TryGetValue
to look if your dictionary already contains that subject. Then you can add the new code to it, otherwise add subject+code:
Dictionary<string, List<string>> dict = new Dictionary<string,List<string>>();
while (dbReader.Read())
{
string code = (string)dbReader["CODE"];
string subject = (string)dbReader["SUBJECT"];
List<string> codes;
if (dict.TryGetValue(subject, out codes))
{
codes.Add(code);
}
else
{
codes = new List<string>() { code };
dict.Add(subject, codes);
}
}
It's just more efficient than to lookup twice.
This method combines the functionality of the ContainsKey method and the Item property. If the key is not found, then the value parameter gets the appropriate default value for the type TValue; for example, 0 (zero) for integer types, false for Boolean types, and null for reference types. Use the TryGetValue method if your code frequently attempts to access keys that are not in the dictionary. Using this method is more efficient than catching the KeyNotFoundException thrown by the Item property. This method approaches an O(1) operation.