筛选字典值的列表

  • 本文关键字:列表 字典 筛选 c#
  • 更新时间 :
  • 英文 :

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
}

我有一个字典,将关键字映射到int列表{ key: [ 1, 2, 3, ... ] }

如何过滤字典的值?例如,我想得到{ key: [2, 4, ...] }

使用RemoveAll,它采用Predicate<T>:

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

遍历所有键并为当前键设置过滤列表。

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

最新更新