Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string.Trim() in Dictionary

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.

like image 593
kf198 Avatar asked Oct 22 '25 06:10

kf198


1 Answers

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());
like image 68
Selman Genç Avatar answered Oct 23 '25 20:10

Selman Genç



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!