Reputation: 9043
I am trying to populate a dictionary of which the subject value which is unique have various Code values that should be matched with it.
CODE SUBJECT
7DIM-062 Recruitment and Selection
7DIM-063 Recruitment and Selection
7DIM-064 Recruitment and Selection
7DIM-065 Recruitment and Selection
7DIM-066 Recruitment and Selection
7DIM-067 Recruitment and Selection
7DIM-068 Recruitment and Selection
So what I want is only for Reqruitment and Selection to be added to the Dictionary once as the unique key and then all the corresponding codes to be added to a List. How would I go about in doing this?
Dictionary<string, List<string>> dict = new Dictionary<string,List<string>>();
this is my query
OleDbDataReader dbReader = cmd.ExecuteReader();
while (dbReader.Read())
{
string code = (string)dbReader["CODE"];
string subject = (string)dbReader["SUBJECT"];
//???? this is the point where I would want to add the values
dict.Add(subject, new List<string>().Add(code);
Upvotes: 0
Views: 127
Reputation: 8558
You can use Lookup<string, string>
:
var subjects = new List<KeyValuePair<string, string>>();
while (dbReader.Read())
{
string code = (string)dbReader["CODE"];
string subject = (string)dbReader["SUBJECT"];
subjects.Add(new KeyValuePair<string, string>(subject, code));
}
// ...
var lookup = subjects.ToLookup(x => x.Key, x => x.Value);
var recruitmentAndSelectionCodes = lookup["Recruitment and Selection"].ToList();
// returns
// 7DIM-062
// 7DIM-063
// etc.
Upvotes: 2
Reputation: 460138
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.
Upvotes: 2
Reputation: 17600
First check if your dictionary already has the key, if not add new key with List
initialization.
if (!dict.ContainsKey(subject))
{
dict[subject] = new List<string>();
}
dict[subject].Add(code);
Upvotes: 5