[英]How can I extract a subset of a dictionary into another one in C#?
我想過濾掉一些我不需要進一步處理的字典對。 檢查此示例代碼:
static void Main(string[] args)
{
var source = new Dictionary<string, dynamic>();
source.Add("number", 1);
source.Add("string1", "One");
source.Add("string2", "Two");
source.Add("string3", "Three");
var onlyStrings = source.Where(s => s.Key != "number").ToDictionary(s => s.Key);
}
在這種情況下,onlyStrings是Dictionary<string, KeyValuePair<string, object>>
但我希望只有字符串具有以下對(源字典的子集):
獲得這樣結果的最佳方法是什么?
ToDictionary方法有一個重載,它也允許一個elementSelector委托:
var onlyStrings = source.Where(s => s.Key != "number")
.ToDictionary(dict => dict.Key, dict => dict.Value);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.