我有以下代码片段将字符串值添加到List,然后将列表添加为字典中的键。现在我想打印字典中的键和值,但我无法这样做。任何想法或建议将不胜感激。
Dictionary<List<string>, int> dic = new Dictionary<List<string>, int>();
List<string> mylist = new List<string>();
string[] str = new string[5];
int counter = 0;
for (int i = 0; i < 5; i++)
{
Console.Write("Type Number:");
string test = Console.ReadLine();
mylist.Add(test);
counter++;
}
Console.WriteLine(string.Join(",", mylist));
dic.Add(mylist, counter);
答案 0 :(得分:2)
如果您想string
key
(正如您加入List<string>
所示),请考虑制作Dictionary<string,int>
而不是Dictionary<List<string>,int>
:
Dictionary<string, int> dic = new Dictionary<string, int>(); //note this dict type
List<string> mylist = new List<string>();
string[] str = new string[5];
int counter = 0;
for (int i = 0; i < 5; i++)
{
Console.Write("Type Number:");
string test = Console.ReadLine();
mylist.Add(test);
counter++;
}
string key = string.Join("", mylist); //note this key combination
//you will have key-value pair such as "12345"-5
Console.WriteLine(string.Join(",", mylist)); //note, you will print as "1,2,3,4,5"
dic.Add(key, counter);
并按照已显示的内容打印出来:
foreach(var v in dic)
Console.WriteLine(v.Key.ToString() + " " + v.Value.ToString());
<强>原始强>
在每个foreach
元素上使用Dictionary
即可完成任务:
foreach(var v in dic)
Console.WriteLine(v.Key.ToString() + " " + v.Value.ToString());
foreach
将允许您迭代Dictionary
中的每个元素。
此外,您可以考虑撤销Dictionary
密钥和值:
Dictionary<int, List<string>> dic = new Dictionary<int, List<string>>();
因为从int
致电List<string>
非常罕见。 Key
的{{1}}部分通常更简单。此外,通过Dictionary
作为List<string>
,您必须准确Key
来呼叫List<string>
,但Value
为int
Key
允许您轻松地从List<string>
获取int
。
如果您计划join
List<string>
,则应使用<string,int>
或<int,string>
而不是<List<string>,int>
或<int,List<string>>
答案 1 :(得分:1)
试试这个
foreach(var v in dic)
Console.WriteLine(string.Join("," v.Key) + " " + v.Value.ToString());
尽管如此,您的key
和value
似乎已向后......