문제

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