将List值添加到字典中

时间:2013-02-12 12:18:30

标签: c# idictionary oledbdatareader

我正在尝试填充一个字典,其中唯一的主题值具有应该与之匹配的各种代码值。

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

所以我想要的只是将Reqruitment和Selection作为唯一键添加到Dictionary中,然后将所有相应的代码添加到List中。 我该怎么做呢?

Dictionary<string, List<string>> dict = new Dictionary<string,List<string>>();

这是我的查询

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);

3 个答案:

答案 0 :(得分:5)

首先检查您的词典是否已有密钥,如果没有添加List初始化的新密钥。

if (!dict.ContainsKey(subject))
{
    dict[subject] = new List<string>();    
}

dict[subject].Add(code);

答案 1 :(得分:2)

您可以使用Dictionary.TryGetValue查看您的词典是否已包含该主题。然后你可以添加新代码,否则添加主题+代码:

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);
    }
}

这比查找两次更有效。

  

此方法结合了ContainsKey方法的功能   Item属性。如果未找到密钥,则为value参数   获取TValue类型的相应默认值;例如,0   (零)表示整数类型,false表示布尔类型,null表示   参考类型。如果您的代码经常使用TryGetValue方法   尝试访问不在字典中的键。用这个   方法比捕获引发的KeyNotFoundException更有效   由Item属性。该方法接近O(1)操作。

答案 2 :(得分:2)

您可以使用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.