How to modify the properties of item inside Dictionary?
I have a Dictionary, and I want to modify the property of an item inside the dictionary, how to achieve this? Can I use foreach to modify the item's properties? I has surveyed some posts, they said the reference obtained from foreach is readonly, which can not be modified.
class MyClass
{
public int propA { get; set; }
public string propB { get; set; }
}
class Foo
{
private Dictionary<int, List<MyClass>> mItemMap;
....
public void QueryAndModify() {
// My original thought, find what i want by foreach
foreach(KeyValuePair<int, List<MyClass>> kvp in mItemMap) {
开发者_如何学C foreach(MyClass item in kvp.Value) {
// Can I modify the propB of item by this way ?
if (item.propA == 3) {
item.propB = "I got you.";
}
}
}
}
}
No, you can modify items in-place.
I believe you can modify the values, but cannot remove items from the dictionary from inside the foreach loop.
Your dictionary is a collection of REFERENCES to instances of MyClass. Modifying properties of the instance does not modify the reference that is stored in the dictionary.
While iterating over the collection you can't modify the COLLECTION ( add,remove items from it). You can modify the instances that the references in the collection are pointing to.
I would recommand you get a good C# book and understand values and references before proceeding.
As Roy said, you can.
Consider also restructuring your code:
public void QueryAndModify()
{
foreach( List<MyClass> list in mItemMap.Values )
{
...
}
}
hth
Mario
精彩评论