Remove item from dictionary where value is empty list
Asked Answered
O

3

10

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

IDictionary<int,Ilist<T>> 
Ophthalmia answered 2/5, 2013 at 14:34 Comment(0)
A
27
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.

Aggappera answered 2/5, 2013 at 14:38 Comment(2)
@ClaudioRedi - Thanks, I just noticed that mistake as well. :)Aggappera
I would change f.Value.Count > 0 to f.Value.Any()Solace
M
20

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.

Moskva answered 2/5, 2013 at 14:38 Comment(4)
When calling ToList(), a new list is created?? i don't see the different between creating a new list or creating a new Dictionary.Ophthalmia
@Maro: Yes, it creates a new list (to avoid iterating over the dictionary while modifying it) - but then it still mutates the original dictionary. That's the difference between the first and second versions... sometimes you need to be able to change an existing collection rather than creating a replacement one. Your question didn't specify the requirements around here.Moskva
That first part (removing empties) doesn't work as written. The linq should be dictionary.Where(pair => pair.Value.Count == 0).Select(pair => pair.Key).ToList(); so as to just grab a list of keys (instead of the whole pair).Delmardelmer
@sohtimsso1970: Fixed.Moskva
H
0

Alternative provided just for completeness.

Alternatively (and depending entirely on your usage), do it at the point of amending the list content on the fly as opposed to a batch at a particular point in time. At a time like this it is likely you'll know the key without having to iterate:

var list = dictionary[0];

// Do stuff with the list.

if (list.Count == 0)
{
    dictionary.Remove(0);
}

The other answers address the need to do it ad-hoc over the entire dictionary.

Hittite answered 2/5, 2013 at 14:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.