'Changing specific value in a dictionary while finding it by it's key
I have a dictionary called users, i want to modify/change a specific value withing dictionary while doing that i try to find that value by searching through keys.. i dont know how to change that value into something else :) I'm not sure if its even possible but wonder if its possible what is the syntax.. ty in advance. o/
txtRecoveryCustomerId.Text is a param that is written by user to start recovery process. All is simulation im just trying to learn :)
Dictionary<string, string> users = new Dictionary<string, string>();
users.Add("12345", "666");
foreach (var item in users)
{
if (item.Key.Contains(txtRecoveryCustomerId.Text))
{
//item.Replace(Convert.ToChar(users.Values), Convert.ToChar(txtPasswordChange.Text));
}
}
Solution 1:[1]
You really need to perform two operations, neither of which requires a loop.
- Ensure the user exists (aka: the dictionary contains the key)
- Set the value stored by that key
You can use the following code to accomplish this:
Dictionary<string, string> users = new Dictionary<string, string>();
users.Add("12345", "666");
// reset password if the user exists
if (users.ContainsKey(txtRecoveryCustomerId.Text))
users[txtRecoveryCustomerId.Text] = txtPasswordChange.Text;
Solution 2:[2]
try this
foreach (var item in users)
if (item.Key.Contains(txtRecoveryCustomerId.Text))
{
users[item.Key] = txtPasswordChange.Text;
break;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | John Glenn |
| Solution 2 | Serge |
