Delete item from dictionary, where value is empty list

What is the best way to remove an item from a dictionary where the value is an empty list?

IDictionary<int,Ilist<T>> 
+4
source share
3 answers
 var foo = dictionary .Where(f => f.Value.Count > 0) .ToDictionary(x => x.Key, x => x.Value); 

This will create a new dictionary. If you want to remove in place, John will do the trick.

+12
source

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.

+10
source

An alternative is provided for completeness only.

As an alternative (and completely depends on your use), do this at the time you make changes to the contents of the list on the fly, and not the party at a certain point in time. At such a time, you will probably know the key without having to repeat:

 var list = dictionary[0]; // Do stuff with the list. if (list.Count == 0) { dictionary.Remove(0); } 

Other answers relate to the need to do this ad-hoc throughout the dictionary.

0
source

All Articles