我有这个
foreach (KeyValuePair<string, Object> tempData in tempList.ToDictionary(x => x.Key, y => y.Value))
{
tempData["fahrzeugA"] = "s";
}
但是使用tempData["fahrzeugA"] = "s";
是行不通的。
我得到:
不能将带有 [] 的索引应用于类型的表达式 'System.Collections.Generic.KeyValuePair'
如果我有一个现有的键fahrzeugA
,我想改变它,正确的语法是什么?
你可以应用这个:
var tempList = new List<Test>();
var dic = tempList.ToDictionary(x => x.Key, y => y.Value);
foreach (var tempData in dic)
{
dic[tempData.Key] = "s";
}
您无法更改键值对,因为它是不可变的结构。更改它的唯一方法是创建一个新实例。该实例将独立于字典而存在。
如果要更改字典中的值,请使用字典上的索引器属性来更改值。
即便如此,字典也会立即超出范围,因此设置它也没有用。它不会影响原始列表。
- 检查键值对值属性。它是只读的,无法更改。
-
ToDictionary
创建一个新对象。您无法通过访问原始对象的元素值来更改其元素。 -
您必须从原始列表中删除此特定项目,并重新添加相同键的新项目。
var removeIndex = tempList.FindIndex(kp => kp.Key == "fahrzeugA"); tempList.RemoveAt(removeIndex); tempList.Add(new KeyValuePair<string, string>("fahrzeugA", "s"));
如果有多个"fahrzeugA"项目(它在列表中有效,但在字典中无效),请改用
RemoveAll
。
如果您的tempList
List<KeyValuePair<string, Object>>
键入:
for (var i = 0; i < tempList.Count; ++i) {
if (tempList[i].Key == "fahrzeugA") {
tempList[i] = new KeyValuePair<string, object> ("fahrzeugA", "s"); // KeyValuePair<string, object> might be changed with your own type if you use something else.
break; // If you want to modify only first KeyValuePair.
}
}
如果你成功地将tempList
变成了字典,那么只能有一个"fahrzeugA"(因为所有键都必须是唯一的),所以循环是没有意义的。
你应该能够说:
var dictionary = tempList.ToDictionary(x => x.Key, y => y.Value);
dictionary["fahrzeugA"] = "s";
如果您不想首先创建字典,则可以执行以下操作:
var matchingKeyValuePair = tempList.SingleOrDefault(x => x.Key == "fahrzeugA");
if (matchingKeyValuePair != null) matchingKeyValuePair.Value = "s";
如果使用 .NET KeyValuePair<TKey, TValue>
列表,这是一个不可变的结构,则可以将该值替换为新的 KeyValuePair,如下所示:
var matchingIndex = tempList.FindIndex(x => x.Key == "fahrzeugA");
if (matchingIndex >= 0)
tempList[matchingIndex] = new KeyValuePair<string, string>("fahrzeugA", "s");
请注意,这假设您只有一个项目具有"fahrzeugA"键。