Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove item from dictionary where value is empty list

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

IDictionary<int,Ilist<T>> 
like image 818
Maro Avatar asked May 02 '13 14:05

Maro


2 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, Jon's answer will do the trick.

like image 98
Justin Helgerson Avatar answered Sep 30 '22 19:09

Justin Helgerson


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.

like image 45
Jon Skeet Avatar answered Sep 30 '22 21:09

Jon Skeet