Search code examples
c#idictionary

Getting rid of whitespace in a dictionary


I have a dictionary

Dictionary<string, List<string>> dictGenSubs = new Dictionary<string, List<string>>();

How can I make sure that there is no whitespace in any of the records of the dictionary?


Solution

  • I assume you are talking only about the strings in the list.

    To achieve that goal, you can use this code:

    dictGenSubs = dictGenSubs.ToDictionary(
                      x => x.Key,
                      x => x.Value
                            .Select(x => x.Replace(" ", string.Empty))
                            .ToList());
    

    This creates a new dictionary with new lists as the values of the dictionary. Each string in each list will be adjusted before being added to the new list.

    A more efficient approach would be to update the existing dictionary and the existing lists:

    foreach(var list in dictGenSubs.Values)
    {
        for(int i = 0; i < list.Count; ++i)
            list[i] = list[i].Replace(" ", string.Empty);
    }