【发布时间】:2017-11-25 16:37:21
【问题描述】:
用两个数组填充字典。我不知道如何使用 foreach 从中获取数据列表。示例:a 17, l 16 .... 请告诉我该怎么做?
string[] words = { "a", "l", "c", "d", "h", "o", "t" };
int[] times = { 17, 16, 1, 02, 11, 19, 21 };
Dictionary<string[], int[]> data= new Dictionary<string[], int[]>();
data.Add(words, times);
foreach (KeyValuePair<string[], int[]> pair in data)
{
Console.WriteLine("Key: {0}, Value: {1}", pair.Key, pair.Value);
}
// output: Key: System.String[], Value: System.Int32[]
【问题讨论】:
-
数据列表是什么意思?
-
您的问题不清楚。您的意思是要使用该数据填充字典吗?以什么形式?对于每个单词作为键,将所有数字作为值?每件作品都有一个数字作为值吗?你试过什么?
-
你可能不想要
Dictionary<string[], int[]>你想要Dictionary<string, int> -
目前你只有一个数据块。它的键是
{ "a", "l", "c", "d", "h", "o", "t" };,它的数据是{ 17, 16, 1, 02, 11, 19, 21 }您可以通过data.Keys访问您的字典中的键列表 - 通过var oneDataItem = dict[the key you want to access];访问单个数据项,通过dict.Values访问存储在字典中的所有值。您可以使用foreach (var k in data.Keys) { Console.WriteLine( data[k]); }对存储在字典中的每个键执行某些操作。你需要练习 C# 并阅读 Dict-Msdn -
另外:您可能不想使用
data.Values- 如果您确实需要,这可能表明字典不是精心挑选的数据容器。