所以我以前用 Python 工作,最近切换到 C#。我一直在尝试用 C# 重新创建我的一个 Python 项目,但我陷入了一些涉及字典的问题。在我的 Python 代码的一部分中,我创建了一些字典,每个字典都有两个键,并将所有字典添加到一个列表中:
slot0 = {"itemID": 0, "amount": 0}
slot1 = {"itemID": 0, "amount": 0}
slot2 = {"itemID": 0, "amount": 0}
inv = [slot0, slot1, slot2]
然后,稍后,我遍历了字典列表,并且能够轻松地更改 itemID
键和 amount
键的值:
for slot in inv:
if slot["item"] == 0:
slot["item"] = 2
slot["amount"] += 1
break
然而,在C#中,这似乎并不那么容易。我成功创建了词典并将它们添加到列表中:
Dictionary<string, int> slot0 = new Dictionary<string, int>() { { "itemID", 0 }, { "amount", 0 } };
Dictionary<string, int> slot1 = new Dictionary<string, int>() { { "itemID", 0 }, { "amount", 0 } };
Dictionary<string, int> slot2 = new Dictionary<string, int>() { { "itemID", 0 }, { "amount", 0 } };
List<Dictionary<string, int>> inv = new List<Dictionary<string, int>>();
private void Start()
{
inv.Add(slot0);
inv.Add(slot1);
inv.Add(slot2);
}
但我不确定如何从 Python 代码复制 for
循环。我知道 foreach
是一个东西,我可以将它与 KeyValuePairs 一起使用,但我很确定你不能用它更改多个键的值。如果有人可以提供帮助,那就太好了。对不起,如果我的问题不太清楚;我很乐意澄清。
最佳答案
这可能不是最优雅的解决方案,但它与您在 Python 中拥有的解决方案相匹配。您将 foreach
很好地遍历 Python 的 for
之后的列表。之后,您将字典作为 slot
并简单地使用带有键的索引器来访问和更改它们的值。
// I use `var` because I believe it to be more "csharponic" ;).
foreach (var slot in inv)
{
if (slot["itemID"] == 0) {
slot["itemID"] = 2;
slot["amount"] += 1;
break;
}
}
您可能应该查看 Dictionary docs了解访问词典可能出现的问题。在我的示例中,如果您使用的 key 不存在,您将以 KeyNotFoundException
结束。为了使代码更健壮,按照@Sach 的建议在 if
中添加一个关键检查;像这样:
if (slot.ContainsKey("itemID") && slot["itemID"] == 0) { ... }
为了完整性,您还可以使用 TryGetValue
。
foreach (var slot in inv)
{
var v = 0;
if (slot.TryGetValue("itemID", out v) && v == 0)
{
slot["itemID"] = 2;
slot["amount"] += 1;
break;
}
}
正如@mjwills 在评论中指出的那样,这样做的好处是减少了键查找的次数(有关 out
的更多信息,请参阅 this )。 Item[]
、ContainsKey
和 TryGetValue
“方法 O(1)。
关于c# - 如何遍历包含多个键的字典列表,并更改不同的键值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51201346/