字典一键在代码c#中的许多值

时间:2012-07-20 11:22:52

标签: c# dictionary

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"

}

4 个答案:

答案 0 :(得分:1)

您不能在字典中使用重复的键,因此代码行dict.Add(d.key,d.value);将抛出异常

答案 1 :(得分:1)

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

答案 2 :(得分:0)

创建一个以List<string>为值的字典,然后只需添加值:

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

答案 3 :(得分:0)

添加值时,您必须检查密钥是否存在:

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