本文介绍了字典枚举在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何枚举一个字典?

假设我使用 foreach()进行词典列举。我无法更新 foreach()内的键/值对。所以我想要一些其他方法。

Suppose I use foreach() for dictionay enumeration. I can't update a key/value pair inside foreach(). So I want some other method.

推荐答案

要枚举一个字典,您可以枚举其中的值:

To enumerate a dictionary you either enumerate the values within it:

Dictionary<int, string> dic;

foreach(string s in dic.Values)
{
   Console.WriteLine(s);
}

或KeyValuePairs

or the KeyValuePairs

foreach(KeyValuePair<int, string> kvp in dic)
{
   Console.WriteLine("Key : " + kvp.Key.ToString() + ", Value : " + kvp.Value);
}

或键

foreach(int key in dic.Keys)
{
    Console.WriteLine(key.ToString());
}

如果您想更新字典中的项目,您需要稍微做一些不同的是,因为您在枚举时无法更新实例。您需要做的是枚举不更新的不同集合,如下所示:

If you wish to update the items within the dictionary you need to do so slightly differently, because you can't update the instance while enumerating. What you'll need to do is enumerate a different collection that isn't being updated, like so:

Dictionary<int, string> newValues = new Dictionary<int, string>() { 1, "Test" };
foreach(KeyValuePair<int, string> kvp in newValues)
{
   dic[kvp.Key] = kvp.Value; // will automatically add the item if it's not there
}

要删除项目,做所以以类似的方式,枚举我们要删除的项目的集合,而不是字典本身。

To remove items, do so in a similar way, enumerating the collection of items we want to remove rather than the dictionary itself.

List<int> keys = new List<int>() { 1, 3 };
foreach(int key in keys)
{
   dic.Remove(key);
}

这篇关于字典枚举在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 18:43