Well, if you need to do this in place, you can use:
var badKeys = dictionary.Where(pair => pair.Value.Count == 0) .Select(pair => pair.Key) .ToList(); foreach (var badKey in badKeys) { dictionary.Remove(badKey); }
Or if you are happy to create a new dictionary:
var noEmptyValues = dictionary.Where(pair => pair.Value.Count > 0) .ToDictionary(pair => pair.Key, pair => pair.Value);
Note that if you have a chance to change the way you build a dictionary, you might consider creating ILookup
instead of ToLookup
. This is usually simpler than a dictionary, where each value is a list, although they are conceptually very similar. The search has a nice feature, where if you request a missing key, you get an empty sequence instead of an exception or a null reference.
source share