gpt-4-0314· OpenAI
WildChat-4.8M (AI2)
C#如何遍历dictonary
- User
C#如何遍历dictonary
- Assistant
在C#中,遍历Dictionary的方法有几种。这里是几种常用的方法:
方法1:使用foreach循环遍历KeyValuePair
Dictionary<string, int> dictionary = new Dictionary<string, int>(); dictionary.Add("one", 1); dictionary.Add("two", 2); dictionary.Add("three", 3); foreach (KeyValuePair<string, int> kvp in dictionary) { Console.WriteLine("键:{0}, 值:{1}", kvp.Key, kvp.Value); }方法2:使用foreach循环遍历Keys和Values
Dictionary<string, int> dictionary = new Dictionary<string, int>(); dictionary.Add("one", 1); dictionary.Add("two", 2); dictionary.Add("three", 3); foreach (string key in dictionary.Keys) { Console.WriteLine("键:{0}, 值:{1}", key, dictionary[key]); }方法3:使用for循环遍历Keys和Values
Dictionary<string, int> dictionary = new Dictionary<string, int>(); dictionary.Add("one", 1); dictionary.Add("two", 2); dictionary.Add("three", 3); var keys = dictionary.Keys.ToArray(); for (int i = 0; i < dictionary.Count; i++) { Console.WriteLine("键:{0}, 值:{1}", keys[i], dictionary[keys[i]]); }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.