gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:51:18 25 4
gpt4 key购买 nike

我有以下代码片段,用于将字符串值添加到列表,然后将该列表作为键添加到字典中。现在我想打印字典中的键和值,但我无法这样做。任何想法或建议将不胜感激。

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

最佳答案

如果你想要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 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>>

关于c# - 从C#中的字典中获取列表的列表值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35773439/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com