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?

有帮助吗?

解决方案

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

其他提示

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));
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top