How do I trim the Keys and Values of a Dictionary?
var Dictionary = new Dictionary<string, string>();
Dictionary.Add("String1 ", " String");
Dictionary.Add(" String2 ", " String ");
Dictionary.Add(" String3 ", " String ");
foreach (var KeyValuePair in Dictionary)
{
KeyValuePair.Key.Trim();
KeyValuePair.Value.Trim();
}
Does not seem to have any impact whatsoever.
Trim returns a new string, you need to assign it back. But you can't change the dictionary while iterating.Instead you can create a new dictionary with trimmed keys and values:
var newDictionary = Dictionary.ToDictionary(x => x.Key.Trim(), x => x.Value.Trim());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With