What is the best way to remove item from dictionary where the value is an empty list?
IDictionary<int,Ilist<T>>
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.
f.Value.Count > 0
to f.Value.Any()
–
Solace 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.
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 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.
© 2022 - 2024 — McMap. All rights reserved.