【问题标题】:Dictionary one key many values in code c#在代码c#中字典一键多值
【发布时间】:2012-07-19 16:03:50
【问题描述】:

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

var c;

var c returns me values : 
100, "somestring"
100,"someotherstring"
200,"two"

foreach(var d in c)
{
 dict.Add(d.key,d.value);
// Need to add key value pairs here for dictionary. if key is same then values should get concatenated.
}

foreach(keyvaluepair<string,List<string>> pair in dictionary)
{
    // This loop should output something like below...
       100,"somestring,someotherstring"
       200,"two"

}

【问题讨论】:

  • 我同意@Duane.. 回到您的旧问题并接受对您有帮助的答案.. 然后我们很乐意为您提供进一步的帮助..

标签: c# dictionary


【解决方案1】:

制作一个以List&lt;string&gt;为值的字典,然后添加值:

foreach(var d in c)
{
  if (!dict.ContainsKey(d.Key))
    dict.Add(d.Key, new List<string>());
  dict[d.Key].Add(d.Value);
}

稍后您可以使用string.Join从列表中获取逗号分隔的字符串

string commaDelimitedList = string.Join(",", valueList.ToArray());

【讨论】:

    【解决方案2】:

    当您添加值时,您必须检查键是否存在:

    if (!dict.ContainsKey(d.key)) {
      dict.Add(d.key, new List<string>());
    }
    dict[d.Key].Add(d.Value);
    

    输出值时,加入字符串:

    Console.Write(pair.Key + ", " + String.Join(", ", pair.Value));
    

    【讨论】:

    • 谢谢 .. 用 pair.toArray() 替换 pair.Value 工作正常
    • @user1502952:是的,旧框架版本需要它。
    【解决方案3】:

    不可能,为此目的创建带有字段 key value 的自己的类

    【讨论】:

    • 是的..那么我应该如何在上面的 foreach 循环中完成这个..这就是我正在寻找的..
    【解决方案4】:

    字典中不能有重复的键,所以代码行 dict.Add(d.key,d.value); 会抛出异常

    【讨论】:

      猜你喜欢
      • 2011-01-07
      • 1970-01-01
      • 2013-02-05
      • 2018-05-19
      • 2016-01-04
      • 1970-01-01
      • 2023-03-24
      • 2011-12-21
      相关资源
      最近更新 更多