简体   繁体   中英

Change the teams of some users

I have a dictionary that keeps a team name ( string ) and the users of the team ( list ). I want to change the teams of some users.

My idea is to find the place of the user who we want to move and remove it from the current collection. Then add the user to the desired team . The problem is I can't find the given user place in the dictionary, thus I am not able to solve it.

var dictionary = new Dictionary<string, List<string>>();

dictionary.Add("Lighter", new List<string>() { "Royal", "JSmith" });
dictionary.Add("Darker", new List<string>() { "DCay", "Rebecca" });

string userToMove = "DCay";
string whereToMove = "Lighter";;
// expected results: 
// Lighter: Royal, JSmith, DCay
// Darker: Rebecca

I did the best I could for this post and I hope it is better than my old ones.

Full code with my comments:

var dictionary = new Dictionary<string, List<string>>();

dictionary.Add("Lighter", new List<string>() { "Royal", "JSmith" });
dictionary.Add("Darker", new List<string>() { "DCay", "Rebecca" });

string userToMove = "DCay";
string whereToMove = "Lighter";

var list = dictionary.Values.SingleOrDefault(l => l.Contains(userToMove));  // list with user name
list?.Remove(userToMove);  // remove user from current list if user in list
dictionary[whereToMove].Add(userToMove); // add user to new list

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM