簡體   English   中英

從字典中刪除值為空列表的項目

[英]Remove item from dictionary where value is empty list

從值為空列表的字典中刪除項目的最佳方法是什么?

IDictionary<int,Ilist<T>> 
var foo = dictionary
    .Where(f => f.Value.Count > 0)
    .ToDictionary(x => x.Key, x => x.Value);

這將創建一個新的字典。 如果你想要就地刪除,Jon的答案就可以解決問題。

好吧,如果你需要就地執行此操作,可以使用:

var badKeys = dictionary.Where(pair => pair.Value.Count == 0)
                        .Select(pair => pair.Key)
                        .ToList();
foreach (var badKey in badKeys)
{
    dictionary.Remove(badKey);
}

或者如果您對創建詞典感到滿意:

var noEmptyValues = dictionary.Where(pair => pair.Value.Count > 0)
                              .ToDictionary(pair => pair.Key, pair => pair.Value);

請注意,如果您有機會更改字典的構造方式,則可以考慮通過ToLookup方法創建ILookup 這通常比字典更簡單,其中每個值都是一個列表,即使它們在概念上非常相似。 查找具有很好的功能,如果您要求缺少鍵,則會得到一個空序列而不是異常或空引用。

替代方案僅為完整性而提供。

或者(完全取決於您的使用情況),在動態修改列表內容時執行此操作,而不是在特定時間點批處理。 在這樣的時候,你可能會知道密鑰而不必迭代:

var list = dictionary[0];

// Do stuff with the list.

if (list.Count == 0)
{
    dictionary.Remove(0);
}

其他答案解決了在整個字典上進行特殊處理的需要。

暫無
暫無

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

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