Question

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?

Was it helpful?

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

OTHER TIPS

Do you mean any whitespace at all in any of the strings in each value? Here's a succinctly inefficient way with LINQ:

bool hasWhitespace = dictGenSubs.SelectMany(kv => kv.Value)
       .Any(s => s.Any(char.IsWhiteSpace));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top