Rav*_*avi 23 .net c# dictionary enumeration
如何枚举字典?
假设我foreach()
用于dictionay枚举.我无法更新里面的键/值对foreach()
.所以我想要一些其他的方法.
Ian*_*Ian 79
要枚举字典,您要枚举其中的值:
Dictionary<int, string> dic;
foreach(string s in dic.Values)
{
Console.WriteLine(s);
}
Run Code Online (Sandbox Code Playgroud)
或KeyValuePairs
foreach(KeyValuePair<int, string> kvp in dic)
{
Console.WriteLine("Key : " + kvp.Key.ToString() + ", Value : " + kvp.Value);
}
Run Code Online (Sandbox Code Playgroud)
或钥匙
foreach(int key in dic.Keys)
{
Console.WriteLine(key.ToString());
}
Run Code Online (Sandbox Code Playgroud)
如果您希望更新字典中的项目,则需要稍微改变一下,因为在枚举时无法更新实例.您需要做的是枚举一个未更新的不同集合,如下所示:
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
}
Run Code Online (Sandbox Code Playgroud)
要删除项目,请以类似的方式执行此操作,枚举我们要删除的项目集合,而不是字典本身.
List<int> keys = new List<int>() { 1, 3 };
foreach(int key in keys)
{
dic.Remove(key);
}
Run Code Online (Sandbox Code Playgroud)
在回答问题"我无法更新foreach()中的值/键"时,您无法在枚举时修改集合.我会通过制作Keys集合的副本来解决这个问题:
Dictionary<int,int> dic=new Dictionary<int, int>();
//...fill the dictionary
int[] keys = dic.Keys.ToArray();
foreach (int i in keys)
{
dic.Remove(i);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
49303 次 |
最近记录: |