簡體   English   中英

作為字典值的過濾器列表

[英]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
}

我有一個字典映射鍵到整數列表{ 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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM