简体   繁体   中英

Filter lists that are dictionary values

Dictionary<int, List<int>> foo = GetFoo();
foreach (var (key, items) in foo)
{
    items = items.Where(item => item % 2 == 0); // unfortunately not in-place
    foo[key] = items; // unfortunately breaks iterator
}

I have a dictionary mapping keys to lists of ints { key: [ 1, 2, 3, ... ] }

How can I filter the values of the dictionary? I want to get { key: [2, 4, ...] } for example.

Use RemoveAll , which takes a Predicate<T> :

foreach (var items in foo.Values)
{
    items.RemoveAll(item => item % 2 == 0);
}

Iterate over all keys and set filtered list for the current key.

foreach (var key in foo.Keys.ToList())
{
    foo[key] = foo[key].Where(item => item % 2 == 0).ToList();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM