用代码C#字典一键很多值 [英] Dictionary one key many values in code c#
本文介绍了用代码C#字典一键很多值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有
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"
}
推荐答案
使用 List< string>
作为值制作字典,然后仅添加值:
Make a dictionary with List<string>
as value, and then just add values :
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());
这篇关于用代码C#字典一键很多值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文