我有一个字典
Dictionary <String, List<Object>> myDictionary;
什么是更新Dictionary的最佳方法,以便从列表中删除已知键的一个对象。例如,我想要从列表中删除第三个对象。
remove函数将根据特定键删除值。 因此,它将删除与该键对应的整个列表。 而我想要更新字典内部的列表。
我有一个字典
Dictionary <String, List<Object>> myDictionary;
Remove
方法。myDictionary.Remove("key");
RemoveAt
方法。List<Object> values;
if (myDictionary.TryGetValue("key", out values))
{
// Here you have access to the list by using values, therefore you can modify your list here
// Make sure, that the list really contains an element at index 3
if (values.Count > 3)
values.RemoveAt(3);
}
if (myDictionary.TryGetValue("key", out List<Object> value)) {
value.RemoveAt(2);
}
List<object>
引用)。value
的引用与Dictionary<>
使用的引用相同,因此您可以使用List.RemoveAt(Int32)从列表中删除第三个。
dict["key1"] = dict["key1"].Where((item, index) => index != 3).ToList();
的方法,但这要求 key 必须存在(否则会抛出 KeyNotFoundException 异常)。因此,这不是一个健壮的解决方案。 - Markus Safar