How to edit data values ​​in a C # dictionary

I have a member dictionary, where the key is a unique long identifier, and the value is an object that contains data about members of the last name and other forms of member details. Is there a way in C # that this can be done?

eg

the dictionary contains a key MemberID 0 member id 0 name bob lives in Italy

Bob moves to England

Is there a way to update the dictionary in C # so that its entry now says that he lives in England?

+3
source share
4 answers

Assuming that Member(or something else) is a class, this is simple:

members[0].Country = "England";

You simply update the object referenced by the dictionary. To go through it is equivalent to:

Member member = members[0];
member.Country = "England";

, , , .

, Member , :

// 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

Member ... , :)

+6

( , , ) :

long theId = ...
yourDictionary[theId].Country = "England"; // fetch and mutate

( , ) , :

long theId = ...
var oldItem = yourDictionary[theId]; // fetch
var newItem = new SomeType(oldItem.Id, oldItem.Name, "England"); // re-create
yourDictionary[theId] = newItem; // overwrite

(, )

(. ) , :

long theId = ...
var item = yourDictionary[theId]; // fetch
item.Country = "England"; // mutate
yourDictionary[theId] = item; // overwrite
+4
dictionary[memberID].Location = "Italy";
+1

, , : ( , .)

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...
}
+1

Source: https://habr.com/ru/post/1779773/


All Articles