How to edit value data in a dictionary C# [duplicate]
I have a dictionary of members where the key is a unique long ID and the value is an object which contains data on that members name surname and other forms of member details. Is there any way in C# that this can be done?
e.g
dictionary key holds memberID 0 member id 0 name is bob lives in Italy
bob moves to England
is there a way to update the dictionary in C# so that his entry now says he lives in England?
Assuming that Member
(or whatever) is a class, it's simple:
members[0].Country = "England";
You're just updating the object which the dictionary has a reference to. Just to step through it, it's equivalent to:
Member member = members[0];
member.Country = "England";
There's only one object representing Bob, and it doesn't matter how you retrieve it.
In fact, if you already have access to the instance of Member
via a different variable, you don't need to use the dictionary at all:
// Assume this will fetch a reference to the same object as is referred
// to by members[0]...
Member bob = GetBob();
bob.Country = "England";
Console.WriteLine(members[0].Country); // Prints England
If Member
is actually a struct... well, then I'd suggest rethinking your design, and making it a class instead :)
For classes (at least, those that are mutable) this should be as simple as:
long theId = ...
yourDictionary[theId].Country = "England"; // fetch and mutate
For structs (which should be immutable; or also for immutable classes), you will need to fetch, re-create, and overwrite:
long theId = ...
var oldItem = yourDictionary[theId]; // fetch
var newItem = new SomeType(oldItem.Id, oldItem.Name, "England"); // re-create
yourDictionary[theId] = newItem; // overwrite
(obviously the re-create line needs tweaking to your particular objects)
In the evil evil world of mutable structs (see comments), you can mutate once it is in a variable:
long theId = ...
var item = yourDictionary[theId]; // fetch
item.Country = "England"; // mutate
yourDictionary[theId] = item; // overwrite
dictionary[memberID].Location = "Italy";
Well, I can't outcode Marc or Jon but here's my entry: (I used City instead of Country but the concept is the same.)
using System;
using System.Collections.Generic;
public class MyClass
{
public static void Main()
{
var dict = new Dictionary<int, Member>();
dict.Add(123, new Member("Jonh"));
dict.Add(908, new Member("Andy"));
dict.Add(456, new Member("Sarah"));
dict[456].City = "London";
Console.WriteLine(dict[456].MemberName + " " + dict[456].City);
Console.ReadKey();
}
}
public class Member
{
public Member(string name) {MemberName = name; City="Austin";}
public string MemberName { get; set; }
public string City { get; set; }
// etc...
}
精彩评论