【问题标题】:adding List values to a dictionary将列表值添加到字典
【发布时间】:2013-02-12 20:32:27
【问题描述】:

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

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

【问题讨论】:

  • 考虑一个 Lookup,它本质上是一个字典,每个键都有多个值。
  • @TimSchmelter 重复键?我不确定 Lookup 中的实现细节,但它确实如您所说:对于每个不同的主题,它会返回一组代码。

标签: c# idictionary oledbdatareader


【解决方案1】:

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

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

dict[subject].Add(code);

【讨论】:

    【解决方案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 方法的功能和 项目属性。如果没有找到key,那么value参数 获取类型 TValue 的适当默认值;例如,0 (零)对于整数类型,对于布尔类型为 false,对于 null 引用类型。如果您的代码经常使用 TryGetValue 方法 尝试访问不在字典中的键。使用这个 方法比捕获抛出的 KeyNotFoundException 更有效 通过 Item 属性。此方法接近 O(1) 操作。

    【讨论】:

      【解决方案3】:

      你可以使用Lookup&lt;string, string&gt;:

      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. 
      

      【讨论】:

      • @TimSchmelter:是的,OP 声明主题是独一无二的,但我看不出它如何影响我的答案。
      • @TimSchmelter:但上面的代码正是这样做的,不是吗?
      猜你喜欢
      • 2015-04-02
      • 1970-01-01
      • 1970-01-01
      • 2018-10-19
      • 1970-01-01
      • 2022-11-05
      • 1970-01-01
      • 1970-01-01
      • 2018-08-27
      相关资源
      最近更新 更多