Dictionary<string,double> myDict = new Dictionary();
//...
foreach (KeyValuePair<string,double> kvp in myDict)
{
kvp.Value = Math.Round(kvp.Value, 3);
}
Run Code Online (Sandbox Code Playgroud)
我收到一个错误:"无法将属性或索引器'System.Collections.Generic.KeyValuePair.Value'分配给它 - 它是只读的."
如何迭代myDict
并更改值?
在 .NET<5 和 .NET Core 3.1 中,以下代码
var d = new Dictionary<string, int> { { "a", 0 }, { "b", 0 }, { "c", 0 } };
foreach (var k in d.Keys)
{
d[k]+=1;
}
Run Code Online (Sandbox Code Playgroud)
投掷
System.InvalidOperationException:集合已修改;枚举操作可能无法执行。
当面向 .NET 5 时,代码段不再抛出。
发生了什么变化?
我未能在Breaking changes in .NET 5和Performance Improvements in .NET 5 中找到答案。
是不是和什么有关ref readonly T
?
我通常使用foreach循环遍历Dictionary.
Dictionary<string, string> dictSummary = new Dictionary<string, string>();
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我想修剪空白的条目,而foreach循环确实不允许这样做.
foreach (var kvp in dictSummary)
{
kvp.Value = kvp.Value.Trim();
}
Run Code Online (Sandbox Code Playgroud)
如何使用for循环执行此操作?
for (int i = dictSummary.Count - 1; i >= 0; i--)
{
}
Run Code Online (Sandbox Code Playgroud) 我有一个包含Person和Count值的字典:
Dictionary<string, int> PersonDictionary = new Dictionary<string, int>();
Run Code Online (Sandbox Code Playgroud)
它具有以下值:
Sally, 6
Beth, 5
Mary, 5
Run Code Online (Sandbox Code Playgroud)
我想交替每个人,并在每次循环时将值减1.我在这个问题上陷入困境
什么是最好的方式来获得莎莉和减1然后去贝丝减1然后去玛丽减1然后再回到莎莉......等等.
只需添加进一步的说明我想循环使用该owner.Key
值并将其传递给另一个方法.所以我需要能够一次遍历这个字典1.
更新:
我的问题有几个问题.一个问题是在循环中递减字典.但我的主要问题是如何迭代每个项目[ Sally -> Beth -> Mary -> Sally
),直到每个人的值变为0 - 这部分仍然是一个大问题.
如何循环具有某个键的dictionarys值?
foreach(somedictionary<"thiskey", x>...?
Run Code Online (Sandbox Code Playgroud)
/ M
我正在尝试搜索字典以查看它是否具有某个值,如果是,则更改它.这是我的代码:
foreach (var d in dictionary)
{
if (d.Value == "red")
{
d.Value = "blue";
}
}
Run Code Online (Sandbox Code Playgroud)
在visual studio中,当我逐步调试代码时,我可以看到它改变了值,然后当它到达foreach循环再次重复它会抛出异常
"集合已被修改;枚举操作可能无法执行"
我该如何解决?
从这个答案:
foreach (var key in dict.Keys.ToList())
{
dict[key] = false;
}
Run Code Online (Sandbox Code Playgroud)
对ToList()的调用使这个工作,因为它正在拉出并(暂时)保存键列表,因此迭代工作.
为什么ToList()
这里需要打电话?
我们正在修改值,而不是钥匙,而且,我最了解,仅modyfying设定一个词典的按键会打破遍历所有键.特别是 - 对我来说,可能是错误的理解 - 只有当我们在字典中添加或删除项目时才能改变键的顺序,我们没有这样做.
请参阅下面的代码.
static void Main(string[] args)
{
// Create Dictionary
var dict = new Dictionary<TestClass, ValueClass>();
// Add data to dictionary
CreateSomeData(dict);
// Create a List
var list = new List<TestClass>();
foreach(var kv in dict) {
// Swap property values for each Key
// For example Key with property value 1 will become 6
// and 6 will become 1
kv.Key.MyProperty = 6 - kv.Key.MyProperty + 1;
// Add the Key to the List
list.Add(kv.Key);
}
// Try to print dictionary …
Run Code Online (Sandbox Code Playgroud)