c# Dictionary 遍历
时间: 2023-08-24 20:06:18 浏览: 51
在 C# 中,你可以使用 `foreach` 循环来遍历 `Dictionary`。以下是一个示例代码:
```csharp
Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary.Add("apple", 1);
dictionary.Add("banana", 2);
dictionary.Add("orange", 3);
foreach (KeyValuePair<string, int> item in dictionary)
{
Console.WriteLine("Key: " + item.Key + ", Value: " + item.Value);
}
```
在上面的示例中,我们创建了一个 `Dictionary` 对象,并向其中添加了一些键值对。然后,使用 `foreach` 循环遍历字典中的每个键值对,并打印出键和对应的值。
请注意,`KeyValuePair<TKey, TValue>` 是一个结构体,用于表示字典中的键值对。你可以通过 `item.Key` 和 `item.Value` 分别访问键和值。
相关问题
c# Dictionary反射遍历
可以使用反射来遍历C#中的Dictionary。下面是一个例子:
```csharp
using System;
using System.Collections.Generic;
using System.Reflection;
class Program
{
static void Main(string[] args)
{
Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("one", 1);
dict.Add("two", 2);
dict.Add("three", 3);
Type dictionaryType = dict.GetType();
MethodInfo getEnumeratorMethod = dictionaryType.GetMethod("GetEnumerator");
IEnumerator<KeyValuePair<string, int>> enumerator = (IEnumerator<KeyValuePair<string, int>>)getEnumeratorMethod.Invoke(dict, null);
while (enumerator.MoveNext())
{
KeyValuePair<string, int> pair = enumerator.Current;
Console.WriteLine(pair.Key + ": " + pair.Value);
}
}
}
```
这里使用了`GetType()`方法获取字典的类型,然后使用`GetMethod()`方法获取`GetEnumerator()`方法的信息。接下来,使用`Invoke()`方法调用`GetEnumerator()`方法,并将其转换为`IEnumerator<KeyValuePair<string, int>>`类型。最后,使用`MoveNext()`方法遍历字典中的键值对,并输出它们的值。
c# 遍历dictionary
在C#中,可以使用foreach循环来遍历Dictionary。Dictionary是一种键值对的集合,每个键都是唯一的。
下面是一个示例代码,展示了如何遍历Dictionary:
```csharp
Dictionary<string, int> myDictionary = new Dictionary<string, int>();
myDictionary.Add("Apple", 1);
myDictionary.Add("Banana", 2);
myDictionary.Add("Orange", 3);
foreach (KeyValuePair<string, int> kvp in myDictionary)
{
Console.WriteLine("Key: " + kvp.Key + ", Value: " + kvp.Value);
}
```
在上面的代码中,我们首先创建了一个Dictionary对象,并添加了几个键值对。然后,使用foreach循环遍历Dictionary中的每个键值对。在循环体内,我们可以通过kvp.Key和kvp.Value来访问每个键值对的键和值。
请注意,Dictionary是无序的,所以遍历的顺序可能与添加键值对的顺序不同。