简体   繁体   中英

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.

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());

Strings are immutable, operations on them never change the string values.

You want to do something like this:

  var trimmedKey = KeyValuePair.Key.Trim();

Besides that, you will want to remove the item and re-add it.

foreach (var kvp in dict)
{
  dict.Remove(kvp.Key)
  dict.Add(kvp.Key.Trim(), kvp.Value.Trim());
}

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