What is the best way to remove item from dictionary where the value is an empty list?
IDictionary<int,Ilist<T>>
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, Jon's answer will do the trick.
Well, if you need to perform this in-place, you could 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're happy creating a new dictionary:
var noEmptyValues = dictionary.Where(pair => pair.Value.Count > 0)
.ToDictionary(pair => pair.Key, pair => pair.Value);
Note that if you get a chance to change the way the dictionary is constructed, you could consider creating an ILookup
instead, via the ToLookup
method. That's usually simpler than a dictionary where each value is a list, even though they're conceptually very similar. A lookup has the nice feature where if you ask for an absent key, you get an empty sequence instead of an exception or a null reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With