【问题标题】:Get a list of data from Dictionary [closed]从字典中获取数据列表[关闭]
【发布时间】: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&lt;string[], int[]&gt; 你想要Dictionary&lt;string, int&gt;
  • 目前你只有一个数据块。它的键是{ "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 - 如果您确实需要,这可能表明字典不是精心挑选的数据容器。

标签: c# .net arrays


【解决方案1】:

从您的示例看来,您正在寻找一个Dictionary&lt;string,int&gt;,对于每个索引,您希望键是words 中的第i 个项目,值是@987654323 中的第i 个项目@。

foreach 方法是:

var dict = new Dictionary<string,int>();
for(int i = 0; i < words.Lenth; i++)
{
    dict.Add(words[i], times[i];
}

请注意,这假定 times 的次数至少与 words 相同,否则将导致 IndexOutOfRangeException

一种 linq 方法将是:

// C# 7.0
var dict = words.Zip(times, (w,t) => (w,t)).ToDictionary(key => key.w, value => value.t);

// C# prior to 7.0
var dict = words.Zip(times, (w,t) => new { w,t })
                .ToDictionary(key => key.w, value => value.t);

请注意,Zip 将按数量较少的集合返回项目。

【讨论】:

    猜你喜欢
    • 2018-05-18
    • 2023-01-24
    • 1970-01-01
    • 2017-07-27
    • 1970-01-01
    • 1970-01-01
    • 2012-11-25
    • 2021-01-30
    • 2021-09-08
    相关资源
    最近更新 更多