-3

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?

dda
  • 6,030
  • 2
  • 25
  • 34
Arianule
  • 8,811
  • 45
  • 116
  • 174

2 Answers2

2

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);
}
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
0

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));
devdigital
  • 34,151
  • 9
  • 98
  • 120
  • 1
    I'm fairly sure that he don't want to know if there's a white-space but he wants to get rid of them(see title). – Tim Schmelter Feb 13 '13 at 12:32
  • Yes, well removing the whitespace before adding them would seem the most logical. Otherwise Daniel's second approach. – devdigital Feb 13 '13 at 12:34