从C#中的字典中获取列表的列表值

时间:2016-03-03 13:25:17

标签: c# dictionary

我有以下代码片段将字符串值添加到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);

2 个答案:

答案 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>,但Valueint 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());

尽管如此,您的keyvalue似乎已向后......