Home > OS >  Filter lists that are dictionary values
Filter lists that are dictionary values

Time:11-09

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.

CodePudding user response:

Use RemoveAll, which takes a Predicate<T>:

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

CodePudding user response:

You can't use the loop variable directly but you can asssign it to a new local variable:

foreach (var (key, items) in foo)
{
    List<int> itemList = items.Where(item => item % 2 == 0).ToList();
    foo[key] = itemList;
}

or use List<T>.RemoveAll in the loop:

foreach (var (key, items) in foo)
{
    items.RemoveAll(i => i % 2 != 0);
}

CodePudding user response:

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();
}
  •  Tags:  
  • c#
  • Related